Sqlite 데이터베이스의 직원 테이블(employee)의 데이터가 그림에 표시되어 있는 것으로 알려져 있습니다.
사용할 수 있는 스크립트는 다음과 같습니다. (이에 따라 변경할 수도 있습니다.)
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');
데이터베이스의 연결 및 동작을 3개의 자바 클래스로 나누어 작성하며, 자바 파일은 다음과 같습니다.
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);
}
}
}
마지막으로 메인 함수를 생성하고 콘솔에서 실행해야 합니다.
메인.자바
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("连接数据库失败!");
}
catch (ClassNotFoundException e){
e.printStackTrace();
JOptionPane.showMessageDialog(null, "加载数据库引擎失败");
}
%>
</body>
</html>
~에
Connection conn= DriverManager.getConnection("jdbc:sqlite:C:/Users/lx/IdeaProjects/demo/identifier.sqlite");
경로는 identifier.sqlite의 절대 경로입니다.
이 방법을 사용하면 아래 그림과 같은 연결 실패 문제가 계속 발생하며 아직 해결 방법을 찾지 못한 경우 추후 추가할 예정입니다.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 갱신
해결: