Friday, July 9, 2010

Using SQLite with SQLiteJDBC driver.

1. SQLite is serverless. With SQLiteJDBC driver, we can write programs to access SQLite using JAVA.
This tutorial will have step by step description about how to do it.

2. We will use Netbeans, but it will work in the same manner with eclipse too.

3. Download SQLiteJDBC driver jar, 'sqlitejdbc-v056.jar' from website: http://www.zentus.com/sqlitejdbc/

4. Create a java project named 'SQLite' in Netbeans.(You can give any name

5. Create a class called 'Test' in that project.

6. Add 'sqlitejdbc-v056.jar' in the class path of 'SQLite' project in Netbeans.

7. Paste following code in Test class


--->
import java.sql.*;

public class Test {

public static void main(String[] args) throws Exception {
Class.forName("org.sqlite.JDBC");
Connection conn =
DriverManager.getConnection("jdbc:sqlite:Vinit");
Statement stat = conn.createStatement();
stat.executeUpdate("drop table if exists school;");
stat.executeUpdate("create table school (name, state);");
PreparedStatement prep = conn.prepareStatement(
"insert into school values (?, ?);");

prep.setString(1, "UTD");
prep.setString(2, "texas");
prep.addBatch();
prep.setString(1, "USC");
prep.setString(2, "california");
prep.addBatch();
prep.setString(1, "MIT");
prep.setString(2, "massachusetts");
prep.addBatch();

conn.setAutoCommit(false);
prep.executeBatch();
conn.setAutoCommit(true);

ResultSet rs = stat.executeQuery("select * from school;");
while (rs.next()) {
System.out.print("Name of School = " + rs.getString("name") + " ");
System.out.println("state = " + rs.getString("state"));
}
rs.close();
conn.close();
}
}


--->

8. Run the project as java application.

9. It will create database file by name 'Vinit' in the Netbeans 'SQLite' project folder.

10. Here is in above code, we are creating sqlite database 'Vinit'.

I hope it will be helpful.

source:
http://www.zentus.com/sqlitejdbc/
http://www.sqlite.org/download.html

1 comment:

Numberguy said...

I know this is a fairly old post, but thank you for it. My question may only be tangentially related, but here it is:

In NetBeans, how I can include my SQLite database file into my project, so that when I build the project, the config.db file (for example) will be included in the dist directory that NetBeans creates??


Thanks.