1.JDBC结构
java程序 ---> 驱动管理器(DriverManager) ---> 驱动(Driver) ---> 数据库(database)
2.步骤
1.导入java.sql API工具包
2.加载驱动
Class.forName("com.mysql.jdbc.Driver");
3.建立与数据库的连接
Connection conn=DriverManager.getConnection(url);
4.创建语句对象
Statement s=conn.createStatement();
preparedStatement=conn.prepareStatement(sql);
5.执行
更新使用execute()或者executeUpdate()
查询使用executeQuery(),配合ResultSet使用
6.关闭语句和连接
先关闭结果集,语句对象,再关闭连接
1)可以在try()里建立连接和创建语句对象,这样会自动关闭
2)在finally{}关闭
3)最后关闭
关闭代码:
try{
if(rs!=null){
rs.close();
rs=null;
}
if(s!=null){
s.close();
s=null
}
if(conn!=null){
conn.close();
conn=null;
}
}catch(Exception e){
e.printStackTrace();
}