文章目录
一、DriverManager 类(其中的Connection有连接对象的意思)
1. DriverManager的作用
- 管理和注册驱动
Class.forName("com.mysql.jdbc.Driver");
- 创建数据库的连接
Connection connection = DriverManager.getConnection(url,user, password);
2. DriverManager的静态方法
1) 通过连接字符串,用户名,密码来得到数据库的连接对象
Connection getConnection (String url, String user, String password)
代码如下:(示例)
//使用用户名、密码、URL 得到连接对象
//用户名 root,密码:1234
String url = "jdbc:mysql://localhost:3306/db";
Connection connection = DriverManager.getConnection(url, "root", 1234);
2)通过连接字符串,属性对象来得到连接对象
Connection getConnection (String url, Properties info)
代码如下:(示例)
//url 连接字符串
String url = "jdbc:mysql://localhost:3306/db";
//属性对象
Properties info = new Properties();
//把用户名和密码放在 info 对象中
info.setProperty("user","root");
info.setProperty("password","1234");
Connection connection = DriverManager.getConnection(url, info);
二、Statement(语句对象)
1. 通过连接对象得到语句对象
// connection是上面定义的连接对象
// Connection connection = DriverManager.getConnection(url, "root", 1234);
statement = conn.createStatement();
2.作用
代表一条语句对象,用于发送 SQL 语句给服务器,用于执行静态 SQL 语句并返回它所生成结果的对象。
3.Statement中的方法
int executeUpdate(String sql)
用于发送 DML 语句,增删改的操作,insert、update、delete
参数:SQL 语句
返回值:返回对数据库影响的行数
ResultSet executeQuery(String sql)
用于发送 DQL 语句,执行查询的操作:select
参数:SQL 语句
返回值:查询的结果集
三、ResultSet(结合Statement的executeQuery方法一起使用)
1. 使用方法
ResultSet rs = statement.executeQuery("select * from student");
2. ResultSet 接口
2.1 作用
作用:封装数据库查询的结果集,对结果集进行遍历,取出每一条记录。
2.2 循环遍历
whlie(rs.next()) {
//获取记录进行处理
}
2.3 解析 boolean next()
游标向下移动1行,判断当前指向的记录是否还有下一条记录,如果返回true,表示还有下一条,否则返回false
2.4 获取记录的两种方式
(1)通过列名:
getint("id"),
getString("name"),
getBoolean("gender"),
getDate("birthday")
(2)通过列号
getlnt(1),
getString(2),
getBoolean(3),
getDate(4)
四、释放资源
1.释放哪些资源 ?
连接对象 Connection
语句对象 Statement
结果对象 ResultMap
2.释放顺序
rs.close();
statement.close();
connection.close();
3.释放原则:先开的后关,后开的先关。
ResultSet
Statement
Connection
4.释放位置 try catch中的finally部分
finally {
//关闭之前要先判断
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
五、PreparedSatement(预编译)
1.作用
(1)解决sql注入的问题,安全性更高。
(2)预编译SQL 语句:可以多次传入不同的参数给 PreparedStatement 对象并执行。减少 SQL 编译次数,提高效率。
prepareStatement会先将sql语句发送给数据库进行预编译,PreparedStatment会引用预编译后的结果
2.使用步骤
2.1 编写 SQL 语句,未知内容使用?占位:“SELECT * FROM user WHERE name=? AND password=?”
String sql = "select * from user where name=? and password=?";
//
2.2 获得 PreparedStatement 对象
Connection connection = JdbcUtils.getConnection();
PreparedStatement ps = connection.prepareStatement(sql);
2.3 设置实际参数:setXxx(占位符的位置, 真实的值)
ps.setString(1, name);
ps.setString(2,password);
ps.setBoolean(3, true);
ps.setDate(4,java.sql.Date.valueOf("1999-11-11"));
2.4 执行参数化 SQL 语句
ResultSet resultSet = ps.executeQuery();
2.5 关闭资源
//释放资源,子接口直接给父接口
JdbcUtils.close(connection,ps,resultSet);
六、事物
获取连接:
connection = JdbcUtils.getConnection();
1.开启事务
connection.setAutoCommit(false);
2.提交事务
connection.commit();