一:首先 添加jar包
二:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JOptionPane;
public
class SqliteDBHepler {
public static void main(String[] args) {
SqliteDBHepler sqlDb = new SqliteDBHepler();
sqlDb.SqliteDBHepler0();
}
private Connection conn=null;
private Statement stat=null;
private ResultSet rs=null;
public SqliteDBHepler(){
SqliteDBHepler0();
}
/**
* 创建数据库、创建表、然后插入数据,最后读出数据
* */
public void SqliteDBHepler0() {
try {
// 创建SQLite的JDBC
Class.forName("org.sqlite.JDBC");
// 建立一个数据库名为activeCode的连接,如果不存在就在当前目录下创建之
String fileName="activeCode.db";
conn = DriverManager.getConnection("jdbc:sqlite:"+fileName);
stat = conn.createStatement();
// 判断该表是否存在,若不存在则创建表ac
String sql = "SELECT COUNT(*) as CNT FROM sqlite_master where type='table' and name='ac'";
boolean exist = false;
rs = stat.executeQuery(sql);
while (rs.next()) {
String count = rs.getString("CNT");
if (count != null && !count.equals("")
&& Integer.parseInt(count) >= 1) {
exist = true;
}
}
if (!exist) {
stat.executeUpdate("create table ac(code varchar(500));");
}
// ResultSet rs=stat.executeQuery("select * from ac");
// while(rs.next()){
// System.out.println("="+rs.getString("code"));
// }
rs.close();
// conn.close();// 结束数据库的连接
} catch (ClassNotFoundException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null,"数据库创建失败"+e.toString());
} catch (SQLException e) {
JOptionPane.showMessageDialog(null,"数据库创建失败"+e.toString());
}
}
//add Data to Database
public boolean save(String sql){
boolean result=true;
try {
stat.executeUpdate(sql);
} catch (SQLException e) {
e.printStackTrace();
result=false;
}
return result;
}
/**
* 判断
数据库表中的是否存在该记录
*
* @throws SQLException
* */
public boolean recordExist(String sql) {
boolean result = false;
try {
System.out.println("sql="+sql);
rs = stat.executeQuery(sql);
if (rs.next()) {
result = true;
} else {
result = false;
}
} catch (SQLException e) {
result = false;
} finally {
try {
if (rs != null) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
return result;
}
// 关闭连接
public void closeConn() {
try {
if(rs!=null){
rs.close();
}
if(stat!=null){
stat.close();
}
if(conn!=null){
conn.close();
}
} catch (SQLException e) {
JOptionPane.showMessageDialog(null,"关闭数据库连接失败"+e.toString());
}
}
}
- java_连接sqlite_数据库.zip (2.1 MB)
- 下载次数: 0