一、JDBC
一、解释
JDBC(java database connectivity): sun公司为了简化和统一java连接数据库,定义的一套规范(API,接口).
在没有jdbc之前,应用程序直接驱动MySql程序来修改数据,不便操作。有了JDBC后,应用程序可以通过JDBC来驱动MySql驱动,来修改数据库,利于操作。
二、 JDBC和驱动的关系
接口(JDBC)与实现(驱动jar包)的关系
三、例子
1.需求
查询所有的用户, 输出到控制台
2.步骤
- 创建Java工程, 拷贝驱动jar包
- 加载驱动
- 获得连接
- 创建执行sql语句对象
- 执行sql语句, 处理结果
- 释放资源
3.代码实现
1.驱动jar包导入项目 工程文件右击-新建文件夹—输入lib文件名—复制mysql驱动到lib目录下—选择工程设置—Modules—jdbc工程文件—Dependencies—点击+号—将JARs放进去 2.代码
public class Test {
public static void main(String[] args) throws Exception{
DriverManager.registerDriver(new Driver());
String url = "jdbc:mysql://localhost:3306/day20_1";
String username = "root";
String password = "root";
Connection connection = DriverManager.getConnection(url,username,password);
Statement statement = connection.createStatement();
String sql = "select * from user";
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
System.out.print(resultSet.getObject(1)+" ");
System.out.print(resultSet.getObject(2)+" ");
System.out.print(resultSet.getObject(3)+" ");
System.out.println(resultSet.getObject(4));
System.out.println("------------------------------------------------");
}
if (resultSet != null){
resultSet.close();
}
if (statement != null){
statement.close();
}
if (connection != null){
connection.close();
}
}
}
4.总结
- 加载\注册驱动
- 获得连接
- 创建执行sql语句对象
- 执行sql语句 处理结果
- 释放资源
二、JDBC的API
一、Drivermanager类
1.registerDriver(Driver driver)
注册驱动
static {
try {
java.sql.DriverManager.registerDriver(new Driver());
} catch (SQLException E) {
throw new RuntimeException("Can't register driver!");
}
}
通过API的方式注册驱动,Driver会new两次,所有推荐这种写法:
Class.forName("com.mysql.jdbc.Driver");
2.getConnection(String url, String user, String password)
与数据库建立连接
二、Connection接口
解释:接口的实现在数据库驱动中。所有与数据库交互都是基于连接对象的。Connection代表连接对象, 是一个接口, 实现在驱动jar包; 操作数据库都是基于Connection的
1.connection.createStatement()
创建执行sql语句对象
2.prepareStatement(String sql)
创建预编译执行sql语句的对象
三、Statement接口
Statement接口的实现在数据库驱动中. 用来操作sql语句(增删改查),并返回相应结果对象
1.ResultSet executeQuery(String sql)
根据查询语句返回结果集。只能执行select语句。
2.int executeUpdate(String sql)
根据执行的DML(insert update delete)语句,返回受影响的行数。
3.boolean execute(String sql)
此方法可以执行任意sql语句。返回boolean值. 【了解】
? true: 执行select有查询的结果
? false: 执行insert, delete,update, 执行select没有查询的结果
四、ResultSet接口
作用: 1.封装结果集,查询结果表的对象;
2.提供一个游标,默认游标指向结果集第一行之前。
3.调用一次next(),游标向下移动一行。
4.提供一些get方法。
1.boolean next();
将光标从当前位置向下移动一行 默认情况下,光标在表头位置,每次调用newt,光标向下移动一行,如果当前行有数据,返回true,如果当前行没数据,返回false。
2.int getInt(int colIndex)
以int形式获取ResultSet结果集当前行指定列号值 getxxx() xxx代表类型 建议通过列名来获取,如果为了等着,建议这个列是什么类型,就通过get类型()来获得。
3.int getInt(String colLabel)
以int形式获取ResultSet结果集当前行指定列名值
4.float getFloat(int colIndex)
以float形式获取ResultSet结果集当前行指定列号值
5.float getFloat(String colLabel)
以float形式获取ResultSet结果集当前行指定列名值**
6.String getString(int colIndex)
以String 形式获取ResultSet结果集当前行指定列号值
7.String getString(String colLabel)
以String形式获取ResultSet结果集当前行指定列名值
8.Date getDate(int columnIndex)
以Date 形式获取ResultSet结果集当前行指定列号值
9.Date getDate(String columnName)
以Date形式获取ResultSet结果集当前行指定列名值
10.void close()
关闭ResultSet 对象
五、封装
定义一个user类
public class User {
private int id;
private String username;
private String password;
private String nickname;
public User() {
}
public User(int id, String username, String password, String nickname) {
this.id = id;
this.username = username;
this.password = password;
this.nickname = nickname;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", nickname='" + nickname + '\'' +
'}';
}
}
封装
List<User> list = new ArrayList<User>();
while (resultSet.next()) {
User user = new User(resultSet.getInt("id"),
resultSet.getString("username"),
resultSet.getString("password"),
resultSet.getString("nickname"));
list.add(user);
}
六、总结
- DriverManager:驱动管理器
- Connection: 代表连接对象
- Statement: 执行sql语句对象
- 执行查询 Result executeQuery(String sql) 返回结果集
- 执行增删改 int excuteUpdate(String sql) 返回受影响的行数
- ResultSet: 结果集
- boolen next() 每调用一次, 光标就向下移动一行; 这个行有数据, 返回true; 没有数据, 返回false
- get类型(String 列名); 根据列名 获得当前列的数据
包名
三、单元测试
一、JUnit介绍
JUnit是一个Java语言的单元测试jar。属于第三方工具,一般情况下需要导入jar包,不过,多数Java开发环境已经集成了JUnit作为单元测试工具.编写测试类,简单理解可以用于取代java的main方法
二、使用
- 在测试类方法上添加注解@Test
- 注解修饰的方法要求:public void 方法名() {…} ,方法名自定义,没有参数。
public class JdbcDemo{
@Test
public void fun01{
System.out.println('测试')
}
}
- 添加IDEA中集成的Junit库,使用快捷键“Alt+Enter”,点击“Add Junit …”
- 使用:选中方法右键,执行当前方法或者选中类名右键,执行类中所有方法(方法必须标记@Test)
三、总结
- 常见使用错误,如果没有添加“@Test”,使用“Junit Test”进行运行,将抛异常
- 单元测试需要注意的地方:
四、JDBC操作数据库例子
一、增删改查
步骤
- 注册驱动
- 获得连接
- 创建执行sql语句对象
- 执行sql语句, 处理结果
- 释放资源
import com.itheima.demo1_JDBC快速入门.User;
import org.junit.Test;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
public class Demo {
@Test
public void insert() throws Exception{
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/day20_1";
String user = "root";
String password = "root";
Connection connection = DriverManager.getConnection(url, user, password);
Statement statement = connection.createStatement();
String sql = "insert into user values(null,'zl','123456','赵六')";
int rows = statement.executeUpdate(sql);
System.out.println("受影响的行数:"+rows);
if (statement != null){
statement.close();
}
if (connection != null){
connection.close();
}
}
@Test
public void update()throws Exception{
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/day20_1";
String user = "root";
String password = "root";
Connection connection = DriverManager.getConnection(url, user, password);
Statement statement = connection.createStatement();
String sql = "update user set password = '123456' where username = 'wangwu'";
int rows = statement.executeUpdate(sql);
System.out.println("受影响的行数:"+rows);
if (statement != null){
statement.close();
}
if (connection != null){
connection.close();
}
}
@Test
public void delete() throws Exception{
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/day20_1";
String user = "root";
String password = "root";
Connection connection = DriverManager.getConnection(url, user, password);
Statement statement = connection.createStatement();
String sql = "delete from user where id = 3";
int rows = statement.executeUpdate(sql);
System.out.println("受影响的行数:"+rows);
if (statement != null){
statement.close();
}
if (connection != null){
connection.close();
}
}
@Test
public void select1() throws Exception{
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/day20_1";
String user = "root";
String password = "root";
Connection connection = DriverManager.getConnection(url, user, password);
Statement statement = connection.createStatement();
String sql = "select * from user";
ResultSet resultSet = statement.executeQuery(sql);
ArrayList<User> list = new ArrayList<>();
while (resultSet.next()) {
User use = new User();
use.setId(resultSet.getInt("id"));
use.setUsername(resultSet.getString("username"));
use.setPassword(resultSet.getString("password"));
use.setNickname(resultSet.getString("nickname"));
list.add(use);
}
if (resultSet != null){
resultSet.close();
}
if (statement != null){
statement.close();
}
if (connection != null){
connection.close();
}
for (User user1 : list) {
System.out.println(user1);
}
}
@Test
public void select2() throws Exception{
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/day20_1";
String user = "root";
String password = "root";
Connection connection = DriverManager.getConnection(url, user, password);
Statement statement = connection.createStatement();
String sql = "select * from user where username = 'zs' and password = '123456'";
ResultSet resultSet = statement.executeQuery(sql);
User use = null;
while (resultSet.next()) {
use = new User();
use.setId(resultSet.getInt("id"));
use.setUsername(resultSet.getString("username"));
use.setPassword(resultSet.getString("password"));
use.setNickname(resultSet.getString("nickname"));
}
if (resultSet != null){
resultSet.close();
}
if (statement != null){
statement.close();
}
if (connection != null){
connection.close();
}
if (use == null){
System.out.println("失败");
}else{
System.out.println("成功");
}
}
}
二、JDBC工具类的抽取
上面的代码有很多公共的地方,所以需要抽取出来
- 在src目录下,创建配置文件
- 定义JdbcUtils类
- 定义getConnection()方法
- 定义release()方法
创建配置文件,配置文件在src目录下,扩展名是properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/day20_1
username=root
password=root
package com.itheima.Utils;
import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
public class JDBCUtils {
private static String driver;
private static String url;
private static String user;
private static String password;
static {
try {
Properties pro = new Properties();
InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("db.properties");
pro.load(is);
url = pro.getProperty("url");
user = pro.getProperty("user");
password = pro.getProperty("password");
driver = pro.getProperty("driver");
Class.forName(driver);
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws Exception {
Connection connection = DriverManager.getConnection(url, user, password);
return connection;
}
public static void release(ResultSet resultSet, Statement statement, Connection connection) {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
注意事项
- 配置文件建议定义在
src目录 - 使用的getProperty()方法里面的参数应该和配置文件里面的key一致, 加""
drive = properties.getProperty("driver")
五、PreparedStatement
一、解释
PreparedStatement预编译SQL语句对象, 是Statemen接口的子接口。 特点:
- 性能要比Statement高
- 会把sql语句先编译,格式固定好,
- sql语句中的参数会发生变化,过滤掉用户输入的关键字(eg: or)
- 可以解决sql注入问题
二、登录验证的sql注入问题
登录说白了就是根据用户名和密码查询数据库, 如果能查询出来就是登录成功, 查询不出来就是登录失败。 首先获得用户输入的账号和密码,通过jdbc,根据用户名和密码查询数据,封装成user对象。判断是否登录成功,说白了就是判断user是否为null,不为null,打印‘登录成功’,为null,打印登录失败。
import com.itheima.demo2_JDBC_API详解.User;
import com.itheima.demo4_JDBC工具类的抽取.JDBCUtils;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Scanner;
public class Test {
public static void main(String[] args) throws Exception{
Scanner sc = new Scanner(System.in);
System.out.println("请输入用户名:");
String username = sc.nextLine();
System.out.println("请输入密码:");
String password = sc.nextLine();
Connection connection = JDBCUtils.getConnection();
Statement statement = connection.createStatement();
String sql = "select * from user where username = '"+username+"' and password = '"+password+"'";
ResultSet resultSet = statement.executeQuery(sql);
User user = null;
while (resultSet.next()) {
user = new User();
user.setId(resultSet.getInt("id"));
user.setUsername(resultSet.getString("username"));
user.setPassword(resultSet.getString("password"));
user.setNickname(resultSet.getString("nickname"));
}
JDBCUtils.release(resultSet,statement,connection);
if (user == null){
System.out.println("登录失败!");
}else{
System.out.println("登录成功,欢迎回来!");
}
}
}
但是当输入的密码 ' or '' = ' , 发现永远登录成功
SELECT * FROM user WHERE username ='zs' AND password = '' or '' = ''
SELECT * FROM user WHERE username ='zs' AND password = '' or true
SELECT * FROM user WHERE true
SELECT * FROM user
发现语句出现了sql注入问题
把用户输入的 or 当成关键词注入到了sql语句里面了
三、preparedStatement解决sql注入问题
1.创建对象
- connection.prepareStatement(String sql) ;创建prepareStatement对象
- sql表示预编译的sql语句,如果sql语句有参数通过?来占位
SELECT * FROM user WHERE username = ? AND password = ?
2.设置参数 prepareStatement.set类型(int i,Object obj);参数1 i 指的就是问号的索引(指第几个问号,从1开始),参数2就是值 eg: setString(1,“zs”); setString(2,“123456”);
3.执行
ResultSet executeQuery(); 执行查询语句
int executeUpdate();执行增删改语句
4.实现
import com.itheima.demo2_JDBC_API详解.User;
import com.itheima.demo4_JDBC工具类的抽取.JDBCUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Scanner;
public class Test {
public static void main(String[] args) throws Exception{
Scanner sc = new Scanner(System.in);
System.out.println("请输入用户名:");
String username = sc.nextLine();
System.out.println("请输入密码:");
String password = sc.nextLine();
Connection connection = JDBCUtils.getConnection();
String sql = "select * from user where username = ? and password = ?";
PreparedStatement ps = connection.prepareStatement(sql);
ps.setString(1,username);
ps.setString(2,password);
ResultSet resultSet = ps.executeQuery();
User user = null;
while (resultSet.next()) {
user = new User();
user.setId(resultSet.getInt("id"));
user.setUsername(resultSet.getString("username"));
user.setPassword(resultSet.getString("password"));
user.setNickname(resultSet.getString("nickname"));
}
JDBCUtils.release(resultSet,ps,connection);
if (user == null){
System.out.println("登录失败!");
}else{
System.out.println("登录成功,欢迎回来!");
}
}
}
四、通过PreparedStatement完成增、删、改、查
- 注册驱动
- 获得连接
- 创建预编译sql语句对象
- 设置参数 执行
- 释放资源
import com.itheima.Utils.JDBCUtils;
import com.itheima.demo1_JDBC快速入门.User;
import org.junit.Test;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
public class Demo {
@Test
public void insert() throws Exception{
Connection connection = JDBCUtils.getConnection();
String sql = "insert into user values(null,?,?,?)";
PreparedStatement ps = connection.prepareStatement(sql);
ps.setString(1,"tq" );
ps.setString(2,"123456" );
ps.setString(3,"田七" );
int rows = ps.executeUpdate();
System.out.println("受影响的行数:"+rows);
JDBCUtils.release(null, ps, connection);
}
@Test
public void update() throws Exception{
Connection connection = JDBCUtils.getConnection();
String sql = "update user set password = ? where id = ?";
PreparedStatement ps = connection.prepareStatement(sql);
ps.setString(1,"abcdef" );
ps.setInt(2,7 );
int rows = ps.executeUpdate();
System.out.println("受影响的行数:"+rows);
JDBCUtils.release(null, ps, connection);
}
@Test
public void delete() throws Exception{
Connection connection = JDBCUtils.getConnection();
String sql = "delete from user where id = ?";
PreparedStatement ps = connection.prepareStatement(sql);
ps.setInt(1,5 );
int rows = ps.executeUpdate();
System.out.println("受影响的行数:"+rows);
JDBCUtils.release(null, ps, connection);
}
@Test
public void select1() throws Exception{
Connection connection = JDBCUtils.getConnection();
String sql = "select * from user";
PreparedStatement ps = connection.prepareStatement(sql);
ResultSet resultSet = ps.executeQuery();
ArrayList<User> list = new ArrayList<User>();
while (resultSet.next()) {
User user = new User();
user.setId(resultSet.getInt("id"));
user.setUsername(resultSet.getString("username"));
user.setPassword(resultSet.getString("password"));
user.setNickname(resultSet.getString("nickname"));
list.add(user);
}
JDBCUtils.release(resultSet, ps, connection);
for (User user : list) {
System.out.println(user);
}
}
@Test
public void select2() throws Exception{
Connection connection = JDBCUtils.getConnection();
String sql = "select * from user where username = ?";
PreparedStatement ps = connection.prepareStatement(sql);
ps.setString(1,"zs" );
ResultSet resultSet = ps.executeQuery();
User user = null;
while (resultSet.next()) {
user = new User();
user.setId(resultSet.getInt("id"));
user.setUsername(resultSet.getString("username"));
user.setPassword(resultSet.getString("password"));
user.setNickname(resultSet.getString("nickname"));
}
JDBCUtils.release(resultSet, ps, connection);
System.out.println(user);
}
}
五、API
1.创建预编译sql语句对象
connection.prepareStatement(String sql);
2.设置参数
prepareStatement.set类型(int 第几个问号,Object 值);
3.执行
Result result = prepareStatement.excuteQuery();
int rows = prepareStatement.excuteUpdate();
4注意事项
- ?只能占参数,说白了就是列的值
- ?从1开始计数
- 执行的时候不要传入sql语句
六、JDBC事务的处理
一、常用API
Connection中与事务有关的方法 | 说明 |
---|
setAutoCommit(boolean autoCommit) | 参数是true或false 如果设置为false,表示关闭自动提交,相当于开启事务; 类似sql里面的 start transaction; | void commit() | 提交事务; 类似sql里面的 commit; | void rollback() | 回滚事务; 类似sql里面的 rollback; |
public class Test {
public static void main(String[] args) throws Exception{
Connection connection = JDBCUtils.getConnection();
connection.setAutoCommit(false);
String sql = "update user set password = ? where id = ?";
PreparedStatement ps = connection.prepareStatement(sql);
ps.setString(1, "666666");
ps.setInt(2,6);
int rows = ps.executeUpdate();
System.out.println("受影响的行数:"+rows);
connection.rollback();
JDBCUtils.release(null,ps,connection);
}
}
public class Test {
public static void main(String[] args) {
Connection connection = null;
PreparedStatement ps = null;
try {
connection = JDBCUtils.getConnection();
connection.setAutoCommit(false);
String sql = "update user set password = ? where id = ?";
ps = connection.prepareStatement(sql);
ps.setString(1, "666666");
ps.setInt(2, 6);
int rows = ps.executeUpdate();
System.out.println("受影响的行数:" + rows);
System.out.println(1/0);
connection.commit();
} catch (Exception e) {
e.printStackTrace();
try {
connection.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
} finally {
JDBCUtils.release(null, ps, connection);
}
}
}
小结
connection.setAutoCommit(false); 开启事务
connection.commit();提交事务
connection.rollback();回顾事务
七、转账案例
zs给ls转100, 使用事务进行控制 1.创建数据库
create table account(
id int primary key auto_increment,
name varchar(20),
money double
);
insert into account values (null,'zs',1000);
insert into account values (null,'ls',1000);
insert into account values (null,'ww',1000);
2.连接数据库
public class Test {
public static void main(String[] args) {
Connection connection = null;
PreparedStatement ps1 = null;
PreparedStatement ps2 = null;
try {
connection = JDBCUtils.getConnection();
connection.setAutoCommit(false);
String sql1 = "update account set money = money - ? where name = ?";
String sql2 = "update account set money = money + ? where name = ?";
ps1 = connection.prepareStatement(sql1);
ps2 = connection.prepareStatement(sql2);
ps1.setDouble(1,100);
ps1.setString(2,"zs");
ps1.executeUpdate();
System.out.println(1/0);
ps2.setDouble(1,100);
ps2.setString(2,"ls");
ps2.executeUpdate();
connection.commit();
} catch (Exception e) {
e.printStackTrace();
try {
connection.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
} finally {
JDBCUtils.release(null,ps1,connection);
JDBCUtils.release(null,ps2,null);
}
}
}
小结
- 涉及到两个写的操作,我们一般通过手动事务去控制
- JDBC操作事务API
connection.setAutoCommit(fasle);
connection.commit();
connection.rollback();
|