###使用JDBC的基本步骤
- 注册驱动
//需提前引包:import com.mysql.cj.jdbc.Driver;这个实现新版的包,老版的引包为:import com.mysql.jdbc.Driver;已经不能使用
DriverManager.registerDriver(new Driver());
- 建立连接
//DriverManager.getConnection("jdbc:mysql://localhost:3306/test?serverTimezone=Hongkong&?user=monty&password=greatsqldb");时区一定要写对
//2. 建立连接 参数一: 协议 + 访问的数据库 , 参数二: 用户名 , 参数三: 密码。
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/student?serverTimezone=Hongkong", "root", "root");
- 创建statement
//3. 创建statement , 跟数据库打交道,一定需要这个对象
st = conn.createStatement();
- 执行sql ,得到ResultSet
//4. 执行查询 , 得到结果集
String sql = "select * from t_stu";
rs = st.executeQuery(sql);
- 遍历结果集
//5. 遍历查询每一条记录
while(rs.next()){
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
System.out.println("id="+id + "===name="+name+"==age="+age);
}
- 释放资源
if (rs != null) {
try {
rs.close();
} catch (SQLException sqlEx) { } // ignore
rs = null;
}
Example 5.1. Obtaining a connection from the DriverManager
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
Connection conn = null;
try {
conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/test?serverTimezone=Hongkong","monty","greatsqldb");
// Do something with the Connection
...
} catch (SQLException ex) {
// handle any errors
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
}
Example 5.2. Using java.sql.Statement to execute a SELECT query
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;
// assume that conn is an already created JDBC connection (see previous examples)
Statement stmt = null;
ResultSet rs = null;
try {
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT foo FROM bar");
// or alternatively, if you don't know ahead of time that
// the query will be a SELECT...
if (stmt.execute("SELECT foo FROM bar")) {
rs = stmt.getResultSet();
}
// Now do something with the ResultSet ....
}
catch (SQLException ex){
// handle any errors
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
}
finally {
// it is a good idea to release
// resources in a finally{} block
// in reverse-order of their creation
// if they are no-longer needed
if (rs != null) {
try {
rs.close();
} catch (SQLException sqlEx) { } // ignore
rs = null;
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException sqlEx) { } // ignore
stmt = null;
}
}