Java8下连接数据库进行增删改查(CRDU)操作

源码

本项目源码下载

步骤

1.获取数据库连接

Connection conn = DBUtil.getConnection();

2.创建会话,有两种方式

1.使用Statement创建(因为有注入问题,现今几乎不使用)

Statement  stmt = conn.createStatement();

2.使用PreparedStatement创建(常用)

PreparedStatement ps = conn.prepareStatement(sql);

3.进行具体的增删改查操作

两种情况:
1. 执行增删改操作:需要用到以下语句,它相当于在数据库中按下了执行sql语句的按钮。
注意:它的返回值是受影响的行数,我们通常用这个返回值来判断对数据的增上哎是否成功

ps.executeUpdate();
  1. 执行查询操作:需要用到以下语句:它相当于在数据库中按下了执行sql语句的按钮。
ps.executeQuery();
3.1书写sql语句

分两种情况:
1.步骤2用PreparedStatement创建的会话
2.步骤2用Statement创建的会话
由于Statement已经不怎么使用,本文主要介绍第二种。

  • 在Java中,sql中的问号表示占位符,表示需要有参数来替代这个占位符
  • 占位符可以设置值,用PreparedStatement的对象设置,假如要设置的值是int类型,应该这样写:
ps.setInt(1, id);
  • 类似地,还能设置String、Double等其他类型:
ps.setString(2, name);
ps.setDouble(3, salary);
  • 第一个参数代表第几个占位符(也就是第几个问号),只能传递int类型
  • 第二个参数代表要传入的具体的值

1)增加

insert into employee values(?,?,?,?);

完整的添加过程:

int id = 5;
String name = "张三";
double salalry = 5000.00;
String gender = "男";
// sql 语句
String insertSql= insert into employee values(?,?,?,?);
ps.setInt(1, id);
ps.setString(2, name);
ps.setDouble(3, salary);
ps.setString(4, gender);
// 在数据库中执行增加操作
int count = ps.executeUpdate();
return count;

2)修改

update employee set name=? where id =? 

完整的修改过程:

int id = 5;
String name = "张三";
// sql 语句
String updateSql = "update employee set name=? where id =? ";
ps = conn.prepareStatement(sql);
// 设置第1个占位符的字段为传递过来的name
ps.setString(1, name);
// 设置第2个占位符的值为传递过来的id
ps.setInt(2, 1);        
// 在数据库中执行修改操作
int count = ps.executeUpdate();
return count;

3)删除

delete form employee where id = ? 

完整的删除过程:

int id = 5;
// sql 语句
String deleteSql = "delete form employee where id = ?";
ps = conn.prepareStatement(sql);
ps.setInt(1, id);
// 在数据库中执行删除操作
int count = ps.executeUpdate();
return count;

4)查询

在数据库中查询的结果需要使用Java中的ResultSet类将进行保存。声明如下:
ResultSet rs = ps.executeQuery();

查询分两种情况:
①简单查询
②带参数查询

Ⅰ.简单查询语句:
select * from employee

完整的查询过程:

int id = 5;
// sql 语句
String selectSql = "select * from employee";
ps = conn.prepareStatement(sql);
// 在数据库中执行查询语句,并将结果(查询到的多条记录)赋值给rs
rs = ps.executeQuery();
// 输出查询结果的表头
System.out.println("\tID\tName\tSlary\tGender");
// 将结果集的值取出,并循环输出
while(rs.next()) {
    id = rs.getInt("id");
    name = rs.getString("name");
    salary = rs.getDouble("salary");
    gender = rs.getString("gender");
    // 输出查询结果
    System.out.println("\t"+id+"\t"+name+"\t"+salary+"\t"+gender);
            }
Ⅰ.带参数的查询语句(以按id查询为例,其他查询以此类推):
select * from employee where id = ?

完整的查询过程:

String selectSql1 = "select * from employee where id = ?";
ps = conn.prepareStatement(sql);
// 在数据库中执行查询语句,并将结果(查询到的多条记录)赋值给rs
rs = ps.executeQuery();
        // 设置 id
        ps.setInt(1, id);
        // 输出查询结果的表头
        System.out.println("\tID\tName\tSlary\tGender");
        // 将结果集的值取出,并循环输出
        while(rs.next()) {
            id = rs.getInt("id");
            name = rs.getString("name");
            salary = rs.getDouble("salary");
            gender = rs.getString("gender");
            // 输出查询结果
            System.out.println("\t"+id+"\t"+name+"\t"+salary+"\t"+gender);
        }

完整工具类

这样的操作应该封装成一个工具类重复使用(代码重用原则)

package beans;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import utils.DBUtil;

public class CRUDDemo {
    private  Connection conn = DBUtil.getConnection();
    private PreparedStatement ps;
    private ResultSet rs;

    // 声明结果集中字段
    int id;
    String name;
    double salary;
    String gender;

    /*
     * 添加
     */
    public int insert(String sql,int id,String name,double salary,String gender) throws SQLException {
        ps = conn.prepareStatement(sql);
        // 设置参数
        ps.setInt(1, id);
        ps.setString(2, name);
        ps.setDouble(3, salary);
        ps.setString(4, gender);
        // 在数据库中执行增加操作
        int count = ps.executeUpdate();
        System.out.println("新增了"+count+"条记录");
        return count;
    }

    /*
     * 修改
     */
    public int update(String sql,String name,int id)throws SQLException {
        ps = conn.prepareStatement(sql);
        // 设置第1个占位符的字段为传递过来的name
        ps.setString(1, name);
        // 设置第2个占位符的值为传递过来的id
        ps.setInt(2, 1);
        // 判断数据是否更新成功
        int count = ps.executeUpdate();
        if(count!=0) {
            System.out.println("数据修改成功!");
            System.out.println("修改了了"+count+"条记录");
        }
        return 0;
    }

    /*
     * 删除
     */
    public int delete(String sql,int id) throws SQLException {
        ps = conn.prepareStatement(sql);
        ps.setInt(1, id);
        int count = ps.executeUpdate();
        System.out.println("删除了"+count+"条记录");
        return 0;
    }

    /*
     * 简单查询
     */
    public void select(String sql)throws SQLException {
        ps = conn.prepareStatement(sql);
        // 在数据库中执行查询语句
        rs = ps.executeQuery();
        // 输出查询结果的表头
        System.out.println("\tID\tName\tSlary\tGender");
            // 保存结果集到Java变量中
            while(rs.next()) {
                id = rs.getInt("id");
                name = rs.getString("name");
                salary = rs.getDouble("salary");
                gender = rs.getString("gender");
                // 输出查询结果
                System.out.println("\t"+id+"\t"+name+"\t"+salary+"\t"+gender);
            }
    }

    /*
     * 带条件的查询(以按id查询为例,其他查询以此类推)
     */
    public void select(String sql,int id)throws SQLException {
        ps = conn.prepareStatement(sql);
        // 设置 id
        ps.setInt(1, id);
        // 在数据库中执行查询语句
        rs = ps.executeQuery();     
        // 输出查询结果的表头
        System.out.println("\tID\tName\tSlary\tGender");
        // 保存结果集到Java变量中
        while(rs.next()) {
            id = rs.getInt("id");
            name = rs.getString("name");
            salary = rs.getDouble("salary");
            gender = rs.getString("gender");
            // 输出查询结果
            System.out.println("\t"+id+"\t"+name+"\t"+salary+"\t"+gender);
        }
    }

}

测试类

package test;

import java.sql.SQLException;

import org.junit.jupiter.api.Test;

import beans.CRUDDemo;

class TestCRUDDemo {
    CRUDDemo cd = new CRUDDemo();
    @Test
    void testInsert() throws SQLException {
        // 测试增加
        String insertSql = "insert into employee values(?,?,?,?)";
        cd.insert(insertSql,3,"谢春花",12000.00,"女");
    }

    @Test
    void testUpdate() throws SQLException {
        // 测试修改(更新),假设更新姓名,更新其他字段类似
        String updateSql = "update employee set name=? where id =? ";
        cd.update(updateSql, "银临", 3);
    }

    @Test
    void testDelete() throws SQLException {
        // 测试删除
        String deleteSql = "delete from employee where id = ?";
        cd.delete(deleteSql, 3);
    }

    @Test
    void testSelectString() throws SQLException {
        // 测试查询表中所有数据
        String selectSql = "select * from employee";
        cd.select(selectSql);
    }

    @Test
    void testSelectStringInt() throws SQLException {
        // 测试带条件的查询(以按id查询为例,其他查询以此类推)
        String selectSql1 = "select * from employee where id = ?";
        cd.select(selectSql1,1);
    }

}

猜你喜欢

转载自blog.csdn.net/qq_32106647/article/details/79153448