当前位置:Gxlcms > mysql > 连接数据库模版

连接数据库模版

时间:2021-07-01 10:21:17 帮助过:40人阅读

package com.mingxin.util;import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;import com.mysql.jdbc.ResultSet;import com.mysql.jdbc.Statement;public class ConnectionUtils {private static String driver = com

  1. package com.mingxin.util;
  2. import java.sql.Connection;
  3. import java.sql.DriverManager;
  4. import java.sql.SQLException;
  5. import com.mysql.jdbc.ResultSet;
  6. import com.mysql.jdbc.Statement;
  7. public class ConnectionUtils {
  8. private static String driver = "com.mysql.jdbc.Driver";
  9. private static String url = "jdbc:mysql://127.0.0.1:3306/db_mx";
  10. private static String user = "root";
  11. private static String password = "123456";
  12. private static Connection conn = null;
  13. static{
  14. try {
  15. Class.forName(driver);
  16. } catch (ClassNotFoundException e) {
  17. System.out.println("驱动加载失败..");
  18. e.printStackTrace();
  19. }
  20. }
  21. public static Connection getConnection(){
  22. try {
  23. conn = DriverManager.getConnection(url, user, password);
  24. if(!conn.isClosed()){
  25. System.out.println("Successed connecting to the Database...");
  26. }
  27. } catch (SQLException e) {
  28. System.out.println("数据库连接失败...");
  29. e.printStackTrace();
  30. }
  31. return conn;
  32. }
  33. public static void main(String[] args) {
  34. //
  35. getConnection();
  36. try {
  37. Statement statement = (Statement) conn.createStatement();
  38. String sql = "select * from user";
  39. ResultSet rs = (ResultSet) statement.executeQuery(sql);
  40. String email = null;
  41. String name = null;
  42. String phone = null;
  43. while(rs.next()){
  44. email = rs.getString("u_email");
  45. name = rs.getString("u_name");
  46. phone = rs.getString("u_phone");
  47. System.out.println("u_email=" + email + " ___u_name=" + name + " ____phone=" + phone);
  48. }
  49. } catch (SQLException e) {
  50. e.printStackTrace();
  51. }
  52. }
  53. }

人气教程排行