Java sqlite jdbc 测试

Java sqlite jdbc 测试

sqlitejdbc-v056.jar。

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Test {
  
  /**
   * @author jzh
   * @remark sqlite jdbc 测试
   * @param args
   * @throws ClassNotFoundException
   */
  public static void main(String[] args) throws ClassNotFoundException {
    // 获取当前类生成class所在的路径
    String strPath = Test.class.getClassLoader().getResource("").toString();
    // 获取file:/后面的路径
    strPath = strPath.substring(6);
    // sqlite 所在路径
    String strDBFile = strPath + "test.db";
    
    // load the sqlite-JDBC driver using the current class loader
    Class.forName("org.sqlite.JDBC");

    Connection conn = null;
    try {
      // create a database connection
      conn = DriverManager.getConnection("jdbc:sqlite:" + strDBFile);
      Statement stmt = conn.createStatement();
      stmt.setQueryTimeout(30); // set timeout to 30 sec.

      stmt.executeUpdate("drop table if exists leader");
      stmt.executeUpdate("create table leader (id integer, name string)");
      stmt.executeUpdate("insert into leader values(1, 'howsky')");
      stmt.executeUpdate("insert into leader values(2, 'howsky.net')");
      ResultSet rs = stmt.executeQuery("select * from leader");
      while (rs.next()) {
        // read the result set
        System.out.println("name = " + rs.getString("name"));
        System.out.println("id = " + rs.getInt("id"));
      }
    } catch (SQLException e) {
      // if the error message is "out of memory",
      // it probably means no database file is found
      System.err.println(e.getMessage());
    } finally {
      try {
        if (conn != null)
          conn.close();
      } catch (SQLException e) {
        // connection close failed.
        System.err.println(e);
      }
    }
  }
}

 

发表回复

您的电子邮箱地址不会被公开。