Java

Java操作Sqlite数据库-jdbc连接
  • 楼主 admin
  • 7702025-3-24 09:01:58
Java操作Sqlite数据库步骤:
1. 导入Sqlite jdbc
本文使用sqlite-jdbc-3.7.2.jar,下载地址 http://pan.baidu.com/s/1kVHAGdD
2. 编写jdbc连接代码
  1. public class OpSqliteDB {
  2.    
  3.     private static final String Class_Name = "org.sqlite.JDBC";
  4.     private static final String DB_URL = "jdbc:sqlite:F:\\xxxdatabase.db";

  5.     public static void main(String args[]) {
  6.         // load the sqlite-JDBC driver using the current class loader
  7.         Connection connection = null;
  8.         try {
  9.             connection = createConnection();
  10.             func1(connection);
  11.             System.out.println("Success!");
  12.         }  catch (SQLException e) {
  13.             System.err.println(e.getMessage());
  14.         } catch(Exception e) {
  15.             e.printStackTrace();
  16.         } finally{
  17.             try {
  18.                 if (connection != null)
  19.                     connection.close();
  20.             } catch (SQLException e) {
  21.                 // connection close failed.
  22.                 System.err.println(e);
  23.             }
  24.         }
  25.     }
  26.    
  27.     // 创建Sqlite数据库连接
  28.     public static Connection createConnection() throws SQLException, ClassNotFoundException {
  29.         Class.forName(Class_Name);
  30.         return DriverManager.getConnection(DB_URL);
  31.     }

  32.     public static void func1(Connection connection) throws SQLException {
  33.         Statement statement = connection.createStatement();
  34.         Statement statement1 = connection.createStatement();
  35.         statement.setQueryTimeout(30); // set timeout to 30 sec.
  36.         // 执行查询语句
  37.         ResultSet rs = statement.executeQuery("select * from table_name1");
  38.         while (rs.next()) {
  39.             String col1 = rs.getString("col1_name");
  40.             String col2 = rs.getString("col2_name");
  41.             System.out.println("col1 = " + col1 + "  col2 = " + col2);
  42.             
  43.             System.out.println(location);
  44.             // 执行插入语句操作
  45.             statement1.executeUpdate("insert into table_name2(col2) values('" + col2_value + "')");
  46.             // 执行更新语句
  47.             statement1.executeUpdate("update table_name2 set 字段名1=" +  字段值1 + " where 字段名2='" +  字段值2 + "'");
  48.         }
  49.     }
复制代码



倒序浏览 看全部 全部回复
暂无回复,快来抢沙发
回复