文章目录
1. DriverManager(驱动管理类)作用:
- 注册驱动
- 获取数据库链接
//1.注册驱动
//Class.forName("com.mysql.jdbc.Driver"); 可以省略
//2.获取链接
//String url="jdbc:mysql://127.0.0.1:3306/学生";
String url="jdbc:mysql:///学生"; // 连接本机数据库可以省略
2. Connection(数据库连接对象)作用:
- 获取执行SQL的对象
- 管理事务
Connection connection = DriverManager.getConnection(url, username, password);
//3.定义SQL语句
String sql1 = "update student_list set grade=2 where name='王丽丽'";
String sql2 = "update student_list set grade=2 where name='于兰兰'";
//4.获取执行SQL对象
Statement statement = connection.createStatement();
try {
//开启事务
connection.setAutoCommit(false);
//5.执行SQL
int count1 = statement.executeUpdate(sql1);//受影响行数
//6.处理结果
System.out.println(count1);
//5.执行SQL
int count2 = statement.executeUpdate(sql2);//受影响行数
//6.处理结果
System.out.println(count2);
//提交事务
connection.commit();
} catch (SQLException e) {
//回滚事务
connection.rollback();
e.printStackTrace();
}
//7.释放资源
statement.close();
connection.close();
3. Statement(执行语句):
- 执行SQL语句
4.ResultSet(结果集对象):
- 封装DQL查询语句结果
- 获取查询结果
//3.定义SQL语句
String sql="select * from student_list";
//4.获取Statement对象
Statement statement = connection.createStatement();
//5.执行SQL
ResultSet resultSet = statement.executeQuery(sql);
//6.遍历
while (resultSet.next()){
//获取数据
String name = resultSet.getString("name");
String sex = resultSet.getString("sex");
int grade = resultSet.getInt("grade");
System.out.println(name);
System.out.println(sex);
System.out.println(grade);
System.out.println("--------------------");
}
//7.释放资源
statement.close();
connection.close();
resultSet.close();
5.PreparedStatement
- 预编译SQL语句并执行,预防SQL注入问题
- 预编译开启:?&useServerPrepStmts=true
SQL注入:通过操作输入修改事先定义好的SQL语句,对服务器进行攻击
String url = "jdbc:mysql:///数据库?&useServerPrepStmts=true";
/**
。。。。。。
*/
//2.用户输入
String name = "lyy";
String pwd="123";
//3.定义SQL语句
String sql = "select * from login where username=? and password=?";
//4.获取PreparedStatement对象
PreparedStatement preparedStatement = connection.prepareStatement(sql);
//5.设置参数
preparedStatement.setString(1,name);
preparedStatement.setString(2,pwd);
//6.执行SQL
ResultSet resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
System.out.println("登录成功");
} else {
System.out.println("登录失败");
}
//7.释放资源
preparedStatement.close();
connection.close();
resultSet.close();