1.JDBC介绍
- JDBC (全称Java DataBase Contectivity) :Java与数据库的连接,数据库编程。
- JDBC 是Java语⾔(JDK)为完成数据库的访问操作提供的⼀套统⼀的标准
- 驱动包下载: 下载驱动jar包,下载地址:https://mvnrepository.com/,打开⽹址搜索 mysql 。
1.1搭建环境
1.创建Java项目
2.导入驱动包
2.1在项目下新建一个lib文件夹
2.2复制粘贴驱动包到lib下
2.3 选择驱动包,右键add library
2.JDBC开发步骤
2.1 注册驱动
// 1.加载驱动类
Class.forName("com.mysql.jdbc.Driver");
2.2 获得连接
//2.建立连接
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/javaTest", "root", "123456");
2.3 获得执行语句对象
//获得执行语句对象
Statement statement = connection.createStatement();
2.4 执行sql
//4.编写sql语句
int i = statement.executeUpdate("delete from student id = 2012");
2.5 关流
//5.关流
statement.close();
connection.close();
总代码:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class Demo6 {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//注册驱动
Class.forName("com.mysql.jdbc.Driver");
//获得连接
String url = "jdbc:mysql://localhost:3306/test1";
String user = "root";
String password = "123456";
Connection connection = DriverManager.getConnection(url, user, password);
//获得执行语句对象
Statement statement = connection.createStatement();
//编写sql语句
int i = statement.executeUpdate("delete from student id = 2012");
System.out.println(i);
//关流
statement.close();
connection.close();
}
}
3.java.sql.ResultSet接⼝ (结果集
)
—ResultSet接⼝对象,表⽰查询操作返回的结果集,提供了便利的⽅法⽤于获取结果集中的数据
(1)查询语句,返回记录集 ResultSet
(2)更新语句,返回数字,表示该更新影响的记录数(0,表示未更新,-1表示更新失败)
(3)ResultSet 就是一张二维的表格,我们可以调用rs对象的 next() 方法把“行光标”向下移动一行,当第一次调用 next() 方法时,“行光标”就到了第一行记录的位置,这时就可以使用 ResultSet 提供的 getXXX(int col) 方法来获取指定列的数据了。
xxx getXxx(参数):获取数据
- xxx : 数据类型;如: int getInt(参数) ;String getString(参数)
- 参数
- int类型的参数:列的编号,从1开始
- String类型的参数: 列的名称
String getString(int columnIndex) // 获取指定列的String类型数据;
int getInt(int columnIndex) // 获取指定列的int类型数据;
double getDouble(int columnIndex) // 获取指定列的double类型数据;
boolean getBoolean(int columnIndex) // 获取指定列的boolean类型数据;
Object getObject(int columnIndex) // 获取指定列的Object类型的数据。
String getString(String columnName) // 获取名称为columnName的列的String数据;
int getInt(String columnName) // 获取名称为columnName的列的int数据;
double getDouble(String columnName) // 获取名称为columnName的列的double数据;
boolean getBoolean(String columnName) // 获取名称为columnName的列的boolean数据;
Object getObject(String columnName) // 获取名称为columnName的列的Object数据;
4.PreparedStatement
PreparedStatement作用:
- 预编译SQL语句并执行:预防SQL注入问题
1.获取 PreparedStatement 对象
// SQL语句中的参数值,使用?占位符替代
String sql = "select * from user where username = ? and password = ?";
// 通过Connection对象获取,并传入对应的sql语句
PreparedStatement pstmt = conn.prepareStatement(sql);
2.设置参数值
PreparedStatement对象:set数据类型(参数1,参数2):给 ? 赋值
参数1: ?的位置编号
参数2: ?的值从1 开始
3.执行SQL语句
executeUpdate(); 执行DDL语句和DML语句
executeQuery(); 执行DQL语句
注意:
调用这两个方法时不需要传递SQL语句,因为获取SQL语句执行对象时已经对SQL语句进行预编译了。
使用preparestatement改进登录案例:
import java.sql.*;
import java.util.Scanner;
public class Demo8 {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Scanner scanner = new Scanner(System.in);
//注册驱动
Class.forName("com.mysql.jdbc.Driver");
//获得连接
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test1?useSSL=false","root","123456");
//获得sql语句
String sql = "select username,password from user where username = ? and password = ?";
//获得preparestatement对象
PreparedStatement ps = connection.prepareStatement(sql);
//输入账号密码
System.out.println("输入账号:");
String username = scanner.next();
System.out.println("输入密码:");
String password = scanner.next();
//设置? 的值
ps.setString(1,username);
ps.setString(2,password);
//执行sql语句,结果会返回到结果集
ResultSet resultSet = ps.executeQuery();
if (resultSet.next()){
System.out.println("登陆成功!");
} else{
System.out.println("用户名或者密码输入错误!");
}
//关流
ps.close();
resultSet.close();
connection.close();
}
}
5.ORM
ORM(Object Relationship Mapping)的基本思想
表结构跟类对应; 表中字段和类的属性对应;表中记录和对象对应;让类中的属性名和数据类型尽量和数据库保持一致!
一条记录对应一个对象。将添加完成的对象依次放到集合中(List,Set,Map)
可以将集合进行遍历输出对象。
代码实现:
1.根据表设计类
public class Emp {
private int empno;
private String ename;
private String job;
private int mgr;
private Date hiredate;
private double sal;
private double comm;
private int deptno;
@Override
public String toString() {
return "Emp{" +
"empno=" + empno +
", ename='" + ename + '\'' +
", job='" + job + '\'' +
", mgr=" + mgr +
", hiredate=" + hiredate +
", sal=" + sal +
", comm=" + comm +
", deptno=" + deptno +
'}';
}
public Emp(int empno, String ename, String job, int mgr, Date hiredate, double sal, double comm, int deptno) {
this.empno = empno;
this.ename = ename;
this.job = job;
this.mgr = mgr;
this.hiredate = hiredate;
this.sal = sal;
this.comm = comm;
this.deptno = deptno;
}
public Emp() {
}
//记得写set和get方法
}
2.写查询需求
public class Demo5_select_orm {
public static void main(String[] args) throws Exception {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/java2212?useSSL=false","root","123456");
String sql = "select * from emp";
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
// 创建集合,存储所有对象
ArrayList<Emp> emps = new ArrayList<>( );
while(rs.next()){
int empno = rs.getInt("empno");
String ename = rs.getString("ename");
double sal = rs.getDouble("sal");
int mgr = rs.getInt("mgr");
double comm = rs.getDouble("comm");
int deptno = rs.getInt("deptno");
Date hiredate = rs.getDate("hiredate");
String job = rs.getString("job");
// 封装对象
Emp emp = new Emp(empno,ename,job,mgr,hiredate,sal,comm,deptno);
// 添加集合
emps.add(emp);
}
for (Emp emp : emps) {
System.out.println(emp );
}
// 结果集关流
rs.close();
ps.close();
conn.close();
}
}
6.DBUtil类
DbUtils 是 Apache 组织提供的一个开源 JDBC工具类库,它是对JDBC的简单封装,学习成本极低,并且使用DbUtils能极大简化JDBC编码的工作量,同时也不会影响程序的性能。
import java.sql.*;
/**
* JDBC的工具类
*/
public class DBUtil {
private static Connection conn = null;
private static PreparedStatement pstmt = null;
private static ResultSet rs = null;
private DBUtil(){
}
/**
* 创建一个连接
*/
public static Connection getConnection() {
String url = "jdbc:mysql:// localhost:3306/test?serverTimezone=GMT%2B8";
try {
//加载驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//建立连接
conn = DriverManager.getConnection(url, "root", "123456");
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
/**
* 关闭数据库资源
*/
public static void closeAll() {
try {
if (rs != null) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (pstmt != null) {
pstmt.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 执行insert、update、delelte 三个DML操作
* 传入参数sql语句,以及sql语句中占位符对应的数据
*/
public static int executeUpdate(String sql, Object[] prams){
conn = getConnection();
int n = 0;
try {
pstmt = conn.prepareStatement(sql);
for (int i=0;i<prams.length;i++){
pstmt.setObject(i+1,prams[i]);
}
n=pstmt.executeUpdate();
}catch (SQLException e){
e.printStackTrace();
}
return n;
}
/**
* 执行查询所返回的Resultset对象
*/
public static ResultSet executeQuery(String sql, Object[] prams){
conn = getConnection();
try {
pstmt = conn.prepareStatement(sql);
for (int i=0;i<prams.length;i++){
pstmt.setObject(i+1,prams[i]);
}
rs = pstmt.executeQuery();
}catch (Exception e){
e.printStackTrace();
}
return rs;
}
}
增加数据操作:
public int addUser(String uname, String pwd) {
String sql = "insert into t_user values(default,?,?)";
Object[] prams = {uname, pwd};
int ok = DBUtil.executeUpdate(sql, prams);
DBUtil.closeAll();
return ok;
}
删除数据操作:
String sql = "delete from t_user where uid=?";
Object[] prams = {4};
int ok = DBUtil.executeUpdate(sql, prams);
DBUtil.closeAll();
查询数据操作:
public User login(String uname, String pwd) {
String sql = "select * from t_user where uname=? and pwd=?";
Object[] prams = {uname, pwd};
ResultSet rs = DBUtil.executeQuery(sql, prams);
User user = null;
try {
while (rs.next()) {
int uid = rs.getInt("uid");
String name = rs.getString("uname");
String pwd2 = rs.getString("pwd");
user = new User(uid, name, pwd2);
}
} catch (SQLException e) {
e.printStackTrace();
}
DBUtil.closeAll();
return user;
}