JDBC连接数据的步骤:
- 注册驱动 (只做一次)
- 建立连接(Connection)
- 创建执行SQL的语句(Statement)
- 执行语句
- 处理执行结果(ResultSet)
- 释放资源
// 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 = "";
Connection conn = DriverManager.getConnection(url, user, password);
// 3.创建语句
Statement st = conn.createStatement();
// 4.执行语句
ResultSet rs = st.executeQuery("select * from user");
// 5.处理结果
while (rs.next()) {
System.out.println(rs.getObject(1) + "\t" + rs.getObject(2) + "\t"
+ rs.getObject(3) + "\t" + rs.getObject(4));
}
// 6.释放资源
rs.close();
st.close();
conn.close();