在IDEA中对数据库SQlite进行增删改查的基本操作

已知Sqlite数据库中员工表(employee)的数据如图所示。

在IDEA中对数据库SQlite进行增删改查的基本操作

可能要用到的脚本如下:(也可以对此做出相应的更改)

create table EMPLOYEE
(
  EMP_ID   VARCHAR2(5),
  EMP_NAME VARCHAR2(20),
  JOB      VARCHAR2(10),
  SALARY   NUMBER(7,2),
  DEPT     VARCHAR2(2)
)
;

insert into EMPLOYEE (EMP_ID, EMP_NAME, JOB, SALARY, DEPT)
values ('1', '王楠', 'clerk', 4300, '10');
insert into EMPLOYEE (EMP_ID, EMP_NAME, JOB, SALARY, DEPT)
values ('2', '张静', 'clerk', 4300, '10');
insert into EMPLOYEE (EMP_ID, EMP_NAME, JOB, SALARY, DEPT)
values ('3', '李刚', 'manager', 5000, '20');
insert into EMPLOYEE (EMP_ID, EMP_NAME, JOB, SALARY, DEPT)
values ('4', '马明', 'manager', 5000, '20');

对数据库的连接和操作我们分为三个java类来写,java文件如下所示:(注意:有的地方需要将相应路径改成自己创建的)

Employee.java
package sql;

public class Employee {
    private String empID;
    private String empName;
    private String job;
    private String salary;
    private String dept;

    public Employee() {
    }

    public Employee(String empID, String empName, String job, String salary, String dept) {
        this.empID = empID;
        this.empName = empName;
        this.job = job;
        this.salary = salary;
        this.dept = dept;
    }

    public String getEmpID() {
        return empID;
    }

    public void setEmpID(String empID) {
        this.empID = empID;
    }

    public String getEmpName() {
        return empName;
    }

    public void setEmpName(String empName) {
        this.empName = empName;
    }

    public String getJob() {
        return job;
    }

    public void setJob(String job) {
        this.job = job;
    }

    public String getSalary() {
        return salary;
    }

    public void setSalary(String salary) {
        this.salary = salary;
    }

    public String getDept() {
        return dept;
    }

    public void setDept(String dept) {
        this.dept = dept;
    }
}
ConnectionPool.java
package sql;

import java.sql.*;

import static java.lang.System.out;

public class ConnectionPool {
    public static Connection getConn() {
        Connection conn = null;
        try {
            Class.forName("org.sqlite.JDBC");
            conn = DriverManager.getConnection(
                    "jdbc:sqlite:identifier.sqlite", "", ""
            );
            out.println("database connect success...");
        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        return conn;
    }

    public static void close(Statement stmt, Connection conn) {
        try {
            if (stmt != null) {
                stmt.close();
                out.println("statement close...");
            }
            if (conn != null) {
                conn.close();
                out.println("connection close...");
            }
            out.println("database connect close...");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void close(ResultSet rs, Statement stmt, Connection conn) {
        try {
            if (stmt != null) {
                rs.close();
                out.println("resultset close...");
            }
            if (rs != null) {
                stmt.close();
                out.println("statement close...");
            }
            if (conn != null) {
                conn.close();
                out.println("connection close...");
            }
            out.println("database connect close...");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
EmployeeDao.java
package sql;

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

public class EmployeeDao {
    private Connection conn;
    private PreparedStatement stmt;
    private ResultSet result;

    //对数据的添加
    public void insertEmployee(Employee emp){
        try {
            conn=ConnectionPool.getConn();
            stmt=conn.prepareStatement("insert into employee(emp_id,emp_name,job,salary,dept) values (?,?,?,?,?)");
            stmt.setString(1,emp.getEmpID());
            stmt.setString(2, emp.getEmpName());
            stmt.setString(3, emp.getJob());
            stmt.setString(4, emp.getSalary());
            stmt.setString(5, emp.getDept());
            int result=stmt.executeUpdate();
            if (result>=1){
                System.out.println("添加成功!");
            } else {
                System.out.println("添加失败!");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            ConnectionPool.close(stmt,conn);
        }
    }
    //对数据的修改
    public void modifyEmployee(Employee emp){
        try {
            conn=ConnectionPool.getConn();
            stmt=conn.prepareStatement("update employee set emp_name=?,job=?,salary=?,dept=? where emp_id=?");
            stmt.setString(1, emp.getEmpName());
            stmt.setString(2, emp.getJob());
            stmt.setString(3, emp.getSalary());
            stmt.setString(4, emp.getDept());
            stmt.setString(5,emp.getEmpID());
            int cout=stmt.executeUpdate();
            if (cout>=1){
                System.out.println("修改成功!");
            } else{
                System.out.println("修改失败!");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            ConnectionPool.close(stmt,conn);
        }
    }

    //对数据的删除
    public void deleteEmployeeById(String empId){
        try {
            conn=ConnectionPool.getConn();
            stmt=conn.prepareStatement("delete from employee where emp_id=?");
            stmt.setString(1,empId);
            int cout=stmt.executeUpdate();
            if (cout>=1){
                System.out.println("删除成功!");
            }else {
                System.out.println("删除失败!");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            ConnectionPool.close(stmt,conn);
        }

    }

    //对数据的查询
    public void queryEmpAll(){
        try {
            conn =ConnectionPool.getConn();
            stmt=conn.prepareStatement("select * from employee");
            result=stmt.executeQuery();
            System.out.println("员工编号:\t员工姓名:\t工作:  \t\t薪水:  \t\t部门编号:\t");
            while (result.next()){
                System.out.println(result.getString("EMP_ID")
                        +"\t\t\t"+ result.getString("EMP_NAME")
                        +"\t\t\t"+ result.getString("JOB")
                        +"\t\t"+ result.getString("SALARY")
                        +"\t\t"+ result.getString("DEPT"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            ConnectionPool.close(result,stmt,conn);
        }
    }
}

最后需要建一个主函数并将其在控制台运行

Main.java
package sql;

public class Main {
    public static void printInfo(String info){
        System.out.println("*******************************"+info+"************************************");
    }
    public static void main(String[] args) {
        EmployeeDao empDao=new EmployeeDao();
        Employee emp=new Employee();
        //查看原始信息
        printInfo("原始数据");
        empDao.queryEmpAll();
       // 添加信息
        printInfo("新增员工");
        emp.setEmpID("5");
        emp.setEmpName("张三");
        emp.setJob("clerk");
        emp.setSalary("9000");
        emp.setDept("20");
        empDao.insertEmployee(emp);
        empDao.queryEmpAll();
        //修改信息
        printInfo("修改编号为5的员工工资为1W");
        emp.setEmpID("5");
        //修改姓名
//        emp.setEmpName("张三");
        //修改工作
//        emp.setJob("clerk");
        //修改工资
        emp.setSalary("10000");
        //修改部门编号
//        emp.setDept("20");
        empDao.modifyEmployee(emp);
        empDao.queryEmpAll();
        //删除信息
        printInfo("删除编号为5的员工");
        empDao.deleteEmployeeById("5");
        empDao.queryEmpAll();

    }
}

在控制台的运行结果如下图所示:

jdbc-3.36.0.3.jar" sql.Main
*******************************原始数据************************************
database connect success...

员工编号:    员工姓名:    工作:        薪水:        部门编号:
1           王楠            男        22      10
2           张静            女        21      10
3           李刚            男        20      20
4           马明            男        23      20
resultset close...

statement close...

connection close...

database connect close...

*******************************新增员工************************************
database connect success...

添加成功!
statement close...

connection close...

database connect close...

database connect success...

员工编号:    员工姓名:    工作:        薪水:        部门编号:
1           王楠            男        22      10
2           张静            女        21      10
3           李刚            男        20      20
4           马明            男        23      20
5           张三            clerk       9000        20
resultset close...

statement close...

connection close...

database connect close...

*******************************修改编号为5的员工工资为1W************************************
database connect success...

修改成功!
statement close...

connection close...

database connect close...

database connect success...

员工编号:    员工姓名:    工作:        薪水:        部门编号:
1           王楠            男        22      10
2           张静            女        21      10
3           李刚            男        20      20
4           马明            男        23      20
5           张三            clerk       10000       20
resultset close...

statement close...

connection close...

database connect close...

*******************************删除编号为5的员工************************************
database connect success...

删除成功!
statement close...

connection close...

database connect close...

database connect success...

员工编号:    员工姓名:    工作:        薪水:        部门编号:
1           王楠            男        22      10
2           张静            女        21      10
3           李刚            男        20      20
4           马明            男        23      20
resultset close...

statement close...

connection close...

database connect close...

进程已结束,退出代码为 0

如果想要将数据库放在部署的服务器(即网页上)运行,

则新建一个jsp文件,输入以下代码测试是否可以连接,然后进行相应的数据库操作。

<%@ page import="java.sql.*" %>
<%@ page import="javax.swing.*" %>
<%@ page import="sql.EmployeeDao" %>
<%@ page import="sql.Employee" %>
<%@ page import="sql.Main" %>
<%@ page contenttype="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<% try{ class.forname("org.sqlite.jdbc"); out.println("数据库驱动成功!"); connection conn="DriverManager.getConnection("jdbc:sqlite:C:/Users/lx/IdeaProjects/demo/identifier.sqlite");" out.println("连接数据库成功!"); } catch (sqlexception e){ e.printstacktrace(); out.println("连接数据库失败!"); (classnotfoundexception joptionpane.showmessagedialog(null, "加载数据库引擎失败"); %>

</%></body>
</html>
</%@></%@></%@></%@></%@></%@>

其中

Connection conn= DriverManager.getConnection("jdbc:sqlite:C:/Users/lx/IdeaProjects/demo/identifier.sqlite");

的路径为identifier.sqlite中的绝对路径

在IDEA中对数据库SQlite进行增删改查的基本操作

在IDEA中对数据库SQlite进行增删改查的基本操作

如果使用此办法依旧出现如下图所示连接失败的问题,暂时还没有找到解决的办法,如果找到,后续会补上

在IDEA中对数据库SQlite进行增删改查的基本操作

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~更新

已解决:

https://blog.csdn.net/m0_62404144/article/details/127482811

Original: https://blog.csdn.net/m0_62404144/article/details/126993595
Author: IT菜鸟新手霞霞
Title: 在IDEA中对数据库SQlite进行增删改查的基本操作

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/816316/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球