import java.sql.*; import org.sqlite.JDBC; public class SQLiteTest { public static void main(String[] args) { try { // The SQLite (3.3.8) Database File // This database has one table (pmp_countries) with 3 columns (country_id, country_code, country_name) // It has like 237 records of all the countries I could think of. String fileName = "c:/pmp.db"; // Driver to Use // http://www.zentus.com/sqlitejdbc/index.html Class.forName("org.sqlite.JDBC"); // Create Connection Object to SQLite Database // If you want to only create a database in memory, exclude the +fileName Connection conn = DriverManager.getConnection("jdbc:sqlite:"+fileName); // Create a Statement object for the database connection, dunno what this stuff does though. Statement stmt = conn.createStatement(); // Create a result set object for the statement ResultSet rs = stmt.executeQuery("SELECT * FROM pmp_countries ORDER BY country_name ASC"); // Iterate the result set, printing each column // if the column was an int, we could do rs.getInt(column name here) as well, etc. while (rs.next()) { String id = rs.getString("country_id"); // Column 1 String code = rs.getString("country_code"); // Column 2 String name = rs.getString("country_name"); // Column 3 System.out.println("ID: "+id+" Code: "+code+" Name: "+name); } // Close the connection conn.close(); } catch (Exception e) { // Print some generic debug info System.out.println(e.getMessage()); System.out.println(e.toString()); } } }
1import java.sql.*;
2 import org.sqlite.JDBC;
3 /**
4 * 这是个非常简单的SQLite的Java程序,
5 * 程序中创建数据库、创建表、然后插入数据,
6 * 最后读出数据显示出来
7 * @author zieckey (http://zieckey.cublog.cn)
8 */
9 publicclass TestSQLite{
10 publicstatic void main(String[] args){
11 try{
12 //连接SQLite的JDBC
13 Class.forName("org.sqlite.JDBC");
14 //建立一个数据库名zieckey.db的连接,如果不存在就在当前目录下创建之
15 Connection conn= DriverManager.getConnection("jdbc:sqlite:zieckey.db");
16 Statement stat= conn.createStatement();
17
18 stat.executeUpdate("create table tbl1(name varchar(20), salary int);" );//创建一个表,两列
19 stat.executeUpdate("insert into tbl1 values('ZhangSan',8000);" );//插入数据
20 stat.executeUpdate("insert into tbl1 values('LiSi',7800);" );
21 stat.executeUpdate("insert into tbl1 values('WangWu',5800);" );
22 stat.executeUpdate("insert into tbl1 values('ZhaoLiu',9100);" );
23
24 ResultSet rs= stat.executeQuery("select * from tbl1;");//查询数据
25
26 while (rs.next()) {//将查询到的数据打印出来
27 System.out.print("name =" + rs.getString("name")+ ""); //列属性一
28 System.out.println("salary =" + rs.getString("salary"));//列属性二
29 }
30 rs.close();
31 conn.close();//结束数据库的连接
32 }
33 catch( Exception e )
34 {
35 e.printStackTrace ( );
36 }
37 }
38 }