smeacham

SQLite Example

Sep 18th, 2012
229
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.47 KB | None | 0 0
  1. import java.sql.Connection;
  2. import java.sql.Statement;
  3. import java.sql.DriverManager;
  4. import java.sql.ResultSet;
  5. import java.sql.ResultSetMetaData;
  6. import java.sql.DatabaseMetaData;
  7.  
  8. public class HelloDatabase
  9. {
  10. public static void main (String[] args) throws Exception
  11. {
  12. // register the driver
  13. String sDriverName = "org.sqlite.JDBC";
  14. Class.forName(sDriverName);
  15.  
  16. // now we set up a set of fairly basic string variables to use in the body of the code proper
  17. String sTempDb = "hello.db";
  18. String sJdbc = "jdbc:sqlite";
  19. String sDbUrl = sJdbc + ":" + sTempDb;
  20. // which will produce a legitimate Url for SqlLite JDBC :
  21. // jdbc:sqlite:hello.db
  22. int iTimeout = 30;
  23. String sMakeTable = "CREATE TABLE dummy (id numeric, response text)";
  24. String sMakeInsert = "INSERT INTO dummy VALUES(1,'Hello from the database')";
  25. String sMakeSelect = "SELECT response from dummy";
  26.  
  27. // create a database connection
  28. Connection conn = DriverManager.getConnection(sDbUrl);
  29. try {
  30. Statement stmt = conn.createStatement();
  31. try {
  32. stmt.setQueryTimeout(iTimeout);
  33. stmt.executeUpdate( sMakeTable );
  34. stmt.executeUpdate( sMakeInsert );
  35. ResultSet rs = stmt.executeQuery(sMakeSelect);
  36. try {
  37. while(rs.next())
  38. {
  39. String sResult = rs.getString("response");
  40. System.out.println(sResult);
  41. }
  42. } finally {
  43.     try { rs.close(); } catch (Exception ignore) {}
  44. }
  45. } finally {
  46.     try { stmt.close(); } catch (Exception ignore) {}
  47. }
  48. } finally {
  49.     try { conn.close(); } catch (Exception ignore) {}
  50. }
  51. }
  52.  
  53. }
Advertisement
Add Comment
Please, Sign In to add comment