在Java中使用SQLite的教程2009-12-15 sqlite 林轩我一直想写一个在Java中使用SQLite的例子,但是很长时间都找不到一个真正合适的, 现在我终于找到了,我希望它可以帮助那些像我一样的Java新手走出困惑.测试环境Intel x86 Laptop Windows XP SP2 Java2 JDK 1.5 Update 8 Netbeans IDE 5.0 import java.sql.*; import org.sqlite.JDBC; /** * Very Basic SQLite Database Example * @author Brandon Tanner */ 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()); } } }下载pmp.db– 例子中用到的数据库文件:http://www.pysquared.com/files/Java/JavaSQLiteExample/pmp.dbSQLiteTest.java- Java 源文件:http://www.pysquared.com/files/Java/JavaSQLiteExample/SQLiteTest.javapmp_sqlite.sql– 用来建立数据库(pmp.db)的SQL语句.:http://www.pysquared.com/files/Java/JavaSQLiteExample/pmp_sqlite.sqlsqlite3.exe- SQLite 3.3.8 命令行程序用来创建和访问数据库(非必需).:http://www.pysquared.com/files/Java/JavaSQLiteExample/sqlite3.exesqlitejdbc.zip v027 (based on SQLite 3.3.8)- SQLiteJDBC 驱动.:http://www.pysquared.com/files/Java/JavaSQLiteExample/sqlitejdbc.zipSQLite Administrator- (可选的) 我认为最好的一个免费的图形数据库管理工具,支持SQLite 2/3.:http://sqliteadmin.orbmu2k.de/W3 Schools SQL Tutorial– 强力推荐的一套在线SQL语法教程.:http://www.w3schools.com/sql/default.asp使用步骤下载上面的文件.对我来说最难的事情就是要把这个驱动放在什么地方Netbeans才能找到它. 我是把下载回来的两个文件(sqlitejdbc.dll 和sqlitejdbc.jar)放到了JDK中的JRE下的lib/ext 目录中(我的机器上是E:ProgramsJavajdk1.5.0_08jrelibext,你可能是c:Program FilesJavajdk1.5.0_08jrelibext),这样就Netbeans就可以找到它了.把pmp.db放到C盘的根目录下.看一下SQLiteTest.java中的代码和注释,很抱歉没有文档的说明.启动Netbeans, 创建一个新的工程, 加入我的例子文件然后编译运行. 程序将把数据库中的所有国家输出在标准输出流上.附加说明 我是如何创建这个数据库文件的? 我用上面提供的pmp_sqlite.sql文件. 你可以看到每行SQL语句的后面都以分号结尾. 使用命令行工具, 输入 sqlite3 pmp.db 这样就可以创建一个数据库文件, 然后输入 .read pmp_sqlite.sql 导入SQL建表语句. 最后输入 .exit 保存数据库并退出. 在SQLite的网站上还有更多关于如何使用命令行工具创建和访问数据库的资料.