SQLite for JDBC
Description
SQLite is a open source database engine that can be connected to Java through SQLite JDBC Driver. You can create portable SQL database using SQLite.
Connection
To define a database, set the connection string to the driver class. If the database specified is not exists, a new file created automatically. Now you can execute SQL commands to manage your database.
Requirements
SQLite JDBC Driver jar (sqlite-jdbc-<version>.jar)
You can download it form http://www.javaworkspace.com/connectdatabase/connectSQLite.do
Installation
Copy driver jar file into your Java project and add it to class path. If you use a IDE to develop your Java application, you can simply add the jar file into your project.
Now, SQLite database engine is ready to work with your Java application.
Examples and Code Samples
Create Connection
Following code segment is for initializing database engine and connect to the database file using SQLite JDBC driver. After executing this code automatically creates a database file (d:\\sqlite.db)try {
Class.forName("org.sqlite.JDBC");
Connection c= DriverManager.getConnection("jdbc:sqlite:d:\\sqlite.db");
} catch (Exception ex) {
ex.printStackTrace();
}
Creating Table
When you want to create a new table you can execute normal SQL commands for it. After executing this code segment, it will create a table named 'myTable' on the database file.
try {
Class.forName("org.sqlite.JDBC");
Connection c= DriverManager.getConnection("jdbc:sqlite:d:\\sqlite.db");
c.createStatement().executeUpdate("CREATEtable myTable(id int,name varchar(50))");
} catch (Exception ex) {
ex.printStackTrace();
}
Inserting Data
Now we have to insert data into the table we created using above code. After executing the insert query, it will insert data into the table. I have given values here are, 1 for column id and Saman for column name.
try {
Class.forName("org.sqlite.JDBC");
Connection c= DriverManager.getConnection("jdbc:sqlite:d:\\sqlite.db");
c.createStatement().executeUpdate("INSERT INTO myTable VALUES('1','Saman')");
} catch (Exception ex) {
ex.printStackTrace();
}
Fetching Data
Then you can get values from the data base using select query. Following code segment will fetch
try {
Class.forName("org.sqlite.JDBC");
Connection c= DriverManager.getConnection("jdbc:sqlite:d:\\sqlite.db");
ResultSet rs=c.createStatement().executeQuery("SELECT * FROM myTable");
while(rs.next()){
System.out.println(rs.getInt("id")+" "+rs.getString("name"));
}
rs.close();
} catch (Exception ex) {
ex.printStackTrace();
}
If you have any question, you can comment or email me.

No comments:
Post a Comment