SQLite CURD function in java
Sample Java prg using SQLite .. CURD operation.
Set up sqlite classpath and path to ur machine accordingly.
/**
*
*/
package sample;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
/**
* @author PraveenKumar
*
*/
public class SqlLite_CURD {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
//getConnection();
create();
populateData();
listAllValues();
}
public static Connection getConnection(){
Connection connection=null;
try{
Class.forName("org.sqlite.JDBC");
connection=DriverManager.getConnection("jdbc:sqlite:D:/Praveen/sw/SQL_LITE/test.db");
//String sql="SELECT name FROM sqlite_master WHERE type='table' ;";
// String sql="SELECT * from test ;";
// PreparedStatement stmt=conn.prepareStatement(sql);
// System.out.println("Test");
// ResultSet rs=stmt.executeQuery();
// while(rs.next()){
// System.out.println(""+rs.getInt(1));
//// System.out.println(""+rs.getString(2));
//// System.out.println(""+rs.getInt(3));
// }
}catch(Exception e){
e.printStackTrace();
}
return connection;
}
public static void create(){
String createSQL="CREATE TABLE mytable(id INT,name text, phonenumber INT) ; ";
Connection con=getConnection();
PreparedStatement pstmt=null;
try{
if(con!=null){
pstmt=con.prepareStatement(createSQL);
if(pstmt.execute()) {
System.out.println("Table created ...!!!");
}
}
closeConnection(pstmt, con);
}catch(Exception e){
e.printStackTrace();
}
}
public static void populateData(){
try
{
Connection conn=getConnection();
PreparedStatement pstmt=null;
if(conn!=null){
String insertSQL="INSERT INTO mytable values(?,?,?)";
pstmt=conn.prepareStatement(insertSQL); for(int i=0;i<10 i="" span="">
pstmt.setInt(1,i);
pstmt.setString(2,i+"th data");
pstmt.setInt(3,(8527400+i));
pstmt.execute();
}
}
closeConnection(pstmt, conn);
} catch (Exception e)
{
e.printStackTrace();
}
}
public static void listAllValues(){
try
{
Connection conn=getConnection();
PreparedStatement pstmt=null;
if(conn!=null){
String selectSQL="select * from mytable ;";
pstmt=conn.prepareStatement(selectSQL);
ResultSet rs=pstmt.executeQuery();
while(rs.next()){
System.out.println(""+rs.getInt(1));
System.out.println(""+rs.getString(2));
System.out.println(""+rs.getInt(3));
}
}
closeConnection(pstmt, conn);
} catch (Exception e)
{
e.printStackTrace();
}
}
public static void closeConnection(PreparedStatement pstmt, Connection conn){
try
{
pstmt.close();
conn.close();
} catch (Exception e)
{
e.printStackTrace();
}
}
}10>
Comments