菁英科技(卓目鸟学苑)- 专注软件测试菁英教育
标题:
java-homework
[打印本页]
作者:
5269
时间:
2021-3-15 19:51
标题:
java-homework
package
equ.utils;
import
equ.model.Equ;
import
java.sql.*;
import
java.util.ArrayList;
import
java.util.LinkedList;
import
java.util.List;
/*
操作
sqlite
数
据
库
,
实现对数
据
库
的增
删
改
查
功能。
JDBC Mysql
、
sqlite
有
对对应
的
jar,maven
的官
网
下
载
*/
public class
SqliteDb {
//
连
接
数
据
库
private
Connection connect(){
//jdbc:subprotocol:subname
//ddbc:
数
据
库类
型:
数
据
库
相
对
于工程的路
径
String url =
"jdbc:sqlite:src/equ/db/equ.db"
;
try
{
//
加
载类
Class.
forName
(
"org.sqlite.JDBC"
);
//
连
接
数
据
库
Connection conn = DriverManager.
getConnection
(url);
System.
out
.println(
"
连接数据库成功
"
);
return
conn;
}
catch
(ClassNotFoundException | SQLException e){
System.
out
.println(
"
连接数据库异常,异常信息为:
"
+e.getMessage());
}
return null
;
}
//
断开数
据
库连
接
private void
disconnect(Connection conn){
try
{
conn.close();
}
catch
(SQLException e){
System.
out
.println(
"
断开数据库异常,异常信息为:
"
+e.getMessage());
}
}
//
执
行
sql
语
句
,
执
行
插
入、
删
除、更新
类
的操作,返回
true/false
private boolean
executeUpdate(Connection conn,String sql){
//Statement
是
执
行
sql
语
句的接口
Statement statement =
null
;
try
{
statement = conn.createStatement();
int
count = statement.executeUpdate(sql);
System.
out
.println(
"
执行
sql
语句成功,影响
"
+count+
"
条数据
"
);
statement.close();
return
count >=
1
;
}
catch
(SQLException e){
System.
out
.println(
"
执行
sql
语句异常,异常信息为:
"
+e.getMessage());
}
return false
;
}
//
执
行
sql
语
句,
执
行
查询类
的操作,返回
查询
的
结
果
private
List<Equ> executeQuery(Connection conn, String sql){
List<Equ> equs =
new
ArrayList<>();
Statement statement =
null
;
try
{
statement = conn.createStatement();
ResultSet rs = statement.executeQuery(sql);
if
(rs !=
null
){
//
查询结
果不
为
空
while
(rs.next()){
//
根据列名
获
取每一列的
值
String id = rs.getString(
"id"
);
String name = rs.getString(
"name"
);
String location = rs.getString(
"location"
);
String baoFei = rs.getString(
"baoFei"
);
String buyTime = rs.getString(
"buyTime"
);
String baoFeiTime = rs.getString(
"baoFeiTime"
);
String record = rs.getString(
"record"
);
//
根据
获
取的信息
构
造
Equ
对
象
Equ equ =
new
Equ(id,name,location,baoFei,baoFeiTime,buyTime,record);
equs.add(equ);
}
System.
out
.println(
"
执行
sql
语句,查询到
"
+equs.size()+
"
条语句
"
);
}
}
catch
(SQLException e){
System.
out
.println(
"
执行
sql
语句异常,异常信息为:
"
+e.getMessage());
}
return
equs;
}
欢迎光临 菁英科技(卓目鸟学苑)- 专注软件测试菁英教育 (http://www.zmnxy.com/)
Powered by Discuz! X3.4