The basic operation of adding, deleting, modifying and checking the database SQlite in IDEA

It is known that the data of the employee table (employee) in the Sqlite database is shown in the figure.

 The script that may be used is as follows: (you can also change this accordingly)

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');

We divide the connection and operation of the database into three java classes to write, and the java files are as follows: (Note: In some places, you need to change the corresponding path to your own creation)

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);
        }
    }
}

Finally, you need to create a main function and run it on the console

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();
        
    }
}

The result of running on the console is shown in the figure below: 

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

If you want to run the database on the deployed server (that is, on the web page), 

Then create a new jsp file, enter the following code to test whether it can be connected, and then perform corresponding database operations.

<%@ 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("连接数据库失败!");
    }
    catch (ClassNotFoundException e){
        e.printStackTrace();
        JOptionPane.showMessageDialog(null, "加载数据库引擎失败");
    }
%>

</body>
</html>

in

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

The path is the absolute path in identifier.sqlite

 If you use this method, the problem of connection failure as shown in the figure below still occurs, and no solution has been found yet. If found, it will be added later

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ renew

solved:

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

Guess you like

Origin blog.csdn.net/m0_62404144/article/details/126993595