signed

QiShunwang

“诚信为本、客户至上”

使用JDBC的基本步骤

2021/3/21 8:39:24   来源:

Conclution of a week

##使用JDBC的基本步骤

1.注册驱动

​ DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver());

2.建立连接

参数一:协议+访问的数据库,参数二:用户名,参数三:密码
conn = DriverManager.getConnection(“jdbc:mysql://localhost:3306/db1”,“root”,“3317985”);

3.创建statement

st = conn.createStatement();

4.执行sql,得到ResultSet

String sql =“select * from student2”;
rs = ((java.sql.Statement) 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);

6.释放资源

if(rs !=null){

try{rs.close();}

catch(SQLException sqlEx){}//ignore

rs=null;

}