简单的在Java中使用SQLite的教程

简单的在Java中使用SQLite的教程

http://tech.ddvip.com   2008年02月19日    社区交流

关键字: SQLite 

内容摘要:我一直想写一个在Java中使用SQLite的例子,但是很长时间都找不到一个真正合适的, 现在我终于找到了,我希望它可以帮助那些像我一样的Java新手走出困惑. 

  我一直想写一个在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 – 例子中用到的数据库文件

  SQLiteTest.java - Java 源文件

  pmp_sqlite.sql – 用来建立数据库(pmp.db)的SQL语句.

  sqlite3.exe - SQLite 3.3.8 命令行程序用来创建和访问数据库(非必需).

  sqlitejdbc.zip v027 (based on SQLite 3.3.8) - SQLiteJDBC 驱动.

  SQLite Administrator - (可选的) 我认为最好的一个免费的图形数据库管理工具,支持SQLite 2/3.

  W3 Schools SQL Tutorial – 强力推荐的一套在线SQL语法教程.

  使用步骤

  下载上面的文件.

  对我来说最难的事情就是要把这个驱动放在什么地方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的网站上还有更多关于如何使用命令行工具创建和访问数据库的资料.

猜你喜欢

转载自blog.csdn.net/s_ongfei/article/details/5971223