SQLite是一个单文件的数据库,在单用户情况下是非常小巧实用的。
用java如何连接sqlite呢?首先需要下载sqlite的jdbc驱动程序。
下载驱动程序之后在程序中引用此jar包,然后就可以使用sqlite数据库了。
如下面的例子,我会创建一个test.db的文件,然后创建一个people表,并在people表中插入一条数据, 然后在从people表中取出所有数据。
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; public class Test { public static void main(String[] args) throws Exception { Class.forName("org.sqlite.JDBC"); Connection conn = DriverManager.getConnection("jdbc:sqlite:test.db"); Statement stat = conn.createStatement(); stat.executeUpdate("drop table if exists people;"); stat.executeUpdate("create table people (name, occupation);"); PreparedStatement prep = conn.prepareStatement( "insert into people values (?, ?);"); prep.setString(1, "Gandhi"); prep.setString(2, "politics"); prep.addBatch(); prep.setString(1, "Turing"); prep.setString(2, "computers"); prep.addBatch(); prep.setString(1, "Wittgenstein"); prep.setString(2, "smartypants"); prep.addBatch(); conn.setAutoCommit(false); prep.executeBatch(); conn.setAutoCommit(true); ResultSet rs = stat.executeQuery("select * from people;"); while (rs.next()) { System.out.println("name = " + rs.getString("name")); System.out.println("job = " + rs.getString("occupation")); } rs.close(); conn.close(); } }
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/10850.html