JDBC学习

JDBC (Java Data Base Connectivity) --- java数据库连接,是由一些接口和类构成的API。

static void test() throws SQLException,ClassNotFoundException{

  //1,注册驱动 3种方式

  DriverManager.registerDriver(new com.mysql.jdbc.Driver());  // 第一种

  System.setProperty("jdbc.drivers","com.mysql.jdbc.Driver");   // 第二种

  Class.forName("com.mysql.jdbc.Driver");         // 第三种 推荐方式

  // 2,建立连接

  String url = "jdbc:mysql://localhost:3306/jdbc";

  String user = "root";

  String password = "root";

  Connection conn = DriverManager.getConnection(url,user,password);

  // 3, 创建语句

  Statement st = conn.createStatement();

  // 4, 执行语句

  ResultSet rs = st.executeQuery("select * from user");

  // 5,处理结果

  while(rs.next()){

    rs.getObject(1);

  }

  // 6,释放资源

  rs.close();

  st.close();

  conn.close();

}

实际使用中应对JDBC进行封装。

「Stay Hungry. Stay Foolish.」
原文地址:https://www.cnblogs.com/Bluesgao/p/7613666.html