Java操作Sqlite数据库-jdbc连接

比眉伴天荒 2022-04-01 06:53 619阅读 0赞

https://www.cnblogs.com/popfisher/p/5497206.html

Java操作Sqlite数据库步骤:

  1. 导入Sqlite jdbc

本文使用sqlite-jdbc-3.7.2.jar,下载地址 http://pan.baidu.com/s/1kVHAGdD

  1. 编写jdbc连接代码

复制代码

  1. public class OpSqliteDB {
  2. private static final String Class_Name = "org.sqlite.JDBC";
  3. private static final String DB_URL = "jdbc:sqlite:F:\\xxxdatabase.db";
  4. public static void main(String args[]) {
  5. // load the sqlite-JDBC driver using the current class loader
  6. Connection connection = null;
  7. try {
  8. connection = createConnection();
  9. func1(connection);
  10. System.out.println("Success!");
  11. } catch (SQLException e) {
  12. System.err.println(e.getMessage());
  13. } catch(Exception e) {
  14. e.printStackTrace();
  15. } finally{
  16. try {
  17. if (connection != null)
  18. connection.close();
  19. } catch (SQLException e) {
  20. // connection close failed.
  21. System.err.println(e);
  22. }
  23. }
  24. }
  25. // 创建Sqlite数据库连接
  26. public static Connection createConnection() throws SQLException, ClassNotFoundException {
  27. Class.forName(Class_Name);
  28. return DriverManager.getConnection(DB_URL);
  29. }
  30. public static void func1(Connection connection) throws SQLException {
  31. Statement statement = connection.createStatement();
  32. Statement statement1 = connection.createStatement();
  33. statement.setQueryTimeout(30); // set timeout to 30 sec.
  34. // 执行查询语句
  35. ResultSet rs = statement.executeQuery("select * from table_name1");
  36. while (rs.next()) {
  37. String col1 = rs.getString("col1_name");
  38. String col2 = rs.getString("col2_name");
  39. System.out.println("col1 = " + col1 + " col2 = " + col2);
  40. System.out.println(location);
  41. // 执行插入语句操作
  42. statement1.executeUpdate("insert into table_name2(col2) values('" + col2_value + "')");
  43. // 执行更新语句
  44. statement1.executeUpdate("update table_name2 set 字段名1=" + 字段值1 + " where 字段名2='" + 字段值2 + "'");
  45. }
  46. }

复制代码

以下是其他的一些Sql语句,来自网址:http://www.cnblogs.com/linjiqin/archive/2011/05/26/2059182.html(Android上面使用Sqlite)

查询语句:

  1. select * from 表名 where 条件子句 group by 分组字句 having ... order by 排序子句

如:

  1. select * from person
  2. select * from person order by id desc
  3. select name from person group by name having count(*)>1

分页SQL与mysql类似,下面SQL语句获取5条记录,跳过前面3条记录

  1. select * from Account limit 5 offset 3
  2. 或者
  3. select * from Account limit 3,5

插入语句:

  1. insert into 表名(字段列表) values(值列表)
  2. 如: insert into person(name, age) values(‘传智’,3)

更新语句:

  1. update 表名 set 字段名=值 where 条件子句
  2. 如:update person set name=‘传智‘ where id=10

删除语句:

  1. delete from 表名 where 条件子句
  2. 如:delete from person where id=10

发表评论

表情:
评论列表 (有 0 条评论,619人围观)

还没有评论,来说两句吧...

相关阅读

    相关 JDBC操作SQLite数据库

    SQLite,是一款轻型的数据库,是遵守ACID的关系型数据库管理系统,它的设计目标是嵌入式的,而且目前已经在很多嵌入式产品中使用了它,它占用资源非常的低,在嵌入式设备中,可能