JDBC学习再小结
一、JDBC概念
二、JDBC常用四个核心对象
DriverManager
getConnection();
Connection
createStatement();
prepareStatement();
Statement(PreparedStatement)
ResultSet executeQuery();
int executeUpdate();
boolean execute();
delete from users where id = ?
ps.setInt(1, 5);
ResultSet
next();
getInt();
getString();
getDouble();
getDate();
...
三、编写一个java应用步骤:
1、创建项目,添加jar包
2、编写操作数据库的类
try {
// 加载驱动
Class.forName("com.mysql.jdbc.Driver");
// 创建连接Connection
Connection conn = DriverManager.getConnection("jdbc:mysql:///day06","root","abc");
// 获取执行sql的statement对象
// conn.createStatement();
PreparedStatement ps = conn.prepareStatement("select * from users where id = ? and name = ?");
ps.setInt(1, 5);
ps.setString(2, "tom");
// 执行语句,并返回结果
ResultSet rs = ps.executeQuery();
// 处理结果
while (rs.next()) {
User u = new User();
u.setInt(rs.getInt("id"));
u.setName(rs.getString("name"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
//关闭资源
if (rs != null)
rs.close();
if (ps != null)
ps.close();
if (conn != null)
conn.close();
}