JAvaによるsqliteデータベースの操作
2639 ワード
sqliteデータベースはjavaエンジニアリングのルートディレクトリの下に配置されます.sqlitejdbc.jar、sqljdbc 4.jarサポートが必要です.
1.sqliteデータベースへの接続
2.操作sqliteデータベース
1.sqliteデータベースへの接続
package sqliteDataBase;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class sqlDbConnection {
public sqlDbConnection() throws ClassNotFoundException {
Class.forName("org.sqlite.JDBC");
}
public Connection getConnection() throws SQLException {
Connection conn = DriverManager.getConnection("jdbc:sqlite:local.db");
return conn;
}
}
2.操作sqliteデータベース
package sqliteDataBase;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import entity.Entity;
public class sqlDbDao {
sqlDbConnection sqlConnection = null;
Connection conn = null;
ResultSet rs = null;
Statement stat = null;
public sqlDbDao() throws ClassNotFoundException {
sqlConnection = new sqlDbConnection();
}
// sqlite
public ArrayList<Entity> getsqlDbMessage() {
ArrayList<Entity> list = new ArrayList<Entity>();
try {
conn = sqlConnection.getConnection();
stat = conn.createStatement();
rs = stat.executeQuery("select * from image;");
while (rs.next()) {
Entity entity = new Entity();
entity.id = rs.getString("id");
entity.image = rs.getString("image");
list.add(entity);
}
if (rs != null)
rs.close();
if (stat != null)
stat.close();
System.err.println(" sqlite ");
} catch (SQLException e) {
System.err.println(" sqlite ");
e.printStackTrace();
} finally {
if (conn != null)
try {
conn.close();
} catch (SQLException e) {
System.err.println("sqlite ");
e.printStackTrace();
}
}
return list;
}
// sqlite
public void addSqliteDb(Entity entity) {
try {
conn = sqlConnection.getConnection();
stat = conn.createStatement();
PreparedStatement prep = conn.prepareStatement("insert into image values (?, ?);");
prep.setString(1, "3");
prep.setString(2, entity.image);
prep.addBatch();
conn.setAutoCommit(false);
prep.executeBatch();
conn.setAutoCommit(true);
System.err.println(" sqlite ");
if (stat != null)
stat.close();
} catch (SQLException e) {
System.err.println(" sqlite ");
e.printStackTrace();
} finally {
if (conn != null)
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}