/**
* 执行多个sql更新语句
* @param sqls
* @throws SQLException
* @throws ClassNotFoundException
*/
public void executeUpdate(String...sqls) throws SQLException, ClassNotFoundException {
try {
for (String sql : sqls) {
getStatement().executeUpdate(sql);
}
} finally {
destroyed();
}
}
/**
* 执行数据库更新 sql List
* @param sqls sql列表
* @throws SQLException
* @throws ClassNotFoundException
*/
public void executeUpdate(List<String> sqls) throws SQLException, ClassNotFoundException {
try {
for (String sql : sqls) {
getStatement().executeUpdate(sql);
}
} finally {
destroyed();
}
}
private Connection getConnection() throws ClassNotFoundException, SQLException {
if (null == connection) connection = getConnection(dbFilePath);
return connection;
}
private Statement getStatement() throws SQLException, ClassNotFoundException {
if (null == statement) statement = getConnection().createStatement();
return statement;
}
/**
* 数据库资源关闭和释放
*/
public void destroyed() {
try {
if (null != connection) {
connection.close();
connection = null;
}
if (null != statement) {
statement.close();
statement = null;
}
if (null != resultSet) {
resultSet.close();
resultSet = null;
}
} catch (SQLException e) {
logger.error("Sqlite数据库关闭时异常", e);
}
}
}
ResltSetExtractor.java 结果集处理类
import java.sql.ResultSet;
public interface ResultSetExtractor<T> {
public abstract T extractData(ResultSet rs);
}
RowMapper.java 结果集行数据处理类
import java.sql.ResultSet;
import java.sql.SQLException;
public interface RowMapper<T> {
public abstract T mapRow(ResultSet rs, int index) throws SQLException;
}
SqliteTest.java 测试类
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.junit.Test;
public class SqliteTest {
@Test
public void testHelper() {
try {
SqliteHelper h = new SqliteHelper("testHelper.db");
h.executeUpdate("drop table if exists test;");
h.executeUpdate("create table test(name varchar(20));");
h.executeUpdate("insert into test values('sqliteHelper test');");
List<String> sList = h.executeQuery("select name from test", new RowMapper<String>() {
@Override
public String mapRow(ResultSet rs, int index)
throws SQLException {
return rs.getString("name");
}
});
System.out.println(sList.get(0));
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
测试输出结果
sqliteHelper test
下面关于SQLite相关的内容你可能也喜欢: