Showing posts with label SQLite. Show all posts
Showing posts with label SQLite. Show all posts

Tuesday 16 September 2014

SQLite Save Temporary Database to A File


If you start shell without supplying a filename, you may save temporary database at any time using:

sqlite> .backup MAIN "folder\your_file.extension"
 

Or you can ATTACH an existing database an use SQL methods:


sqlite> ATTACH DATABASE "path\stored.db" AS other;
sqlite> INSERT OR REPLACE INTO other.table1 SELECT * FROM this_table1;
sqlite> DETACH other;

SQLite vacuum

To get rid of -journal files is to do with this command :

sqlite3 mysqlitedatabase.db VACUUM

SQLite Usage With C

1. Download sqlite-amalgamation-3080600.zip file from :

http://www.sqlite.org/download.html

2. Unpack/Compile the contents.

3. Write C files or copy one of the examples.

4. Compile and execute..
   
Example :


/*
    Compile String : cl CreateTable.c -I E:\DATABASE_RESOURCES\SQLITE\3_08_06\ -link sqlite3.obj
*/

#include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h>

static int callback(void *NotUsed, int argc, char **argv, char **azColName){
   int i;
   for(i=0; i<argc; i++){
      printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
   }
   printf("\n");
   return 0;
}

int main(int argc, char* argv[])
{
   sqlite3 *db;
   char *zErrMsg = 0;
   int  rc;
   char *sql;

   /* Open database */
   rc = sqlite3_open("test.db", &db);
   if( rc ){
      fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
      exit(0);
   }else{
      fprintf(stdout, "Opened database successfully\n");
   }

   /* Create SQL statement */
   sql = "CREATE TABLE COMPANY("  \
         "ID INT PRIMARY KEY     NOT NULL," \
         "NAME           TEXT    NOT NULL," \
         "AGE            INT     NOT NULL," \
         "ADDRESS        CHAR(50)," \
         "SALARY         REAL );";

   /* Execute SQL statement */
   rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg);
   if( rc != SQLITE_OK ){
   fprintf(stderr, "SQL error: %s\n", zErrMsg);
      sqlite3_free(zErrMsg);
   }else{
      fprintf(stdout, "Table created successfully\n");
   }
   sqlite3_close(db);
   return 0;
}

SQLite Usage with Java

1. Download Jdbc jar file from :

https://bitbucket.org/xerial/sqlite-jdbc/downloads


2. Add to claspath file

3. Connect to pre-created DB.

    Here is the syntax of database connection URL for file system database:

        jdbc:sqlite:database_file_path

    Where database_file_path can be either relative or absolute path. For example:

        jdbc:sqlite:product.db
        jdbc:sqlite:C:/work/product.db

    And here is the syntax of database connection URL for memory database:

        jdbc:sqlite::memory:
        jdbc:sqlite:

4. Load SQLite JDBC driver

    Class.forName("org.sqlite.JDBC");
   
Or:
    DriverManager.registerDriver(new org.sqlite.JDBC());

5. Sample Code and executions
   
   
package sqlite;

import java.sql.*;

public class TestSQLite {
    public static void main(String[] args) {
        TestSQLite t = new TestSQLite();
        t.selectExsistingDb();
    }

    private void selectExistingDb() {
        Connection c = null;
        Statement stmt = null;
        try {
            Class.forName("org.sqlite.JDBC");
            c = DriverManager.getConnection("jdbc:sqlite:E:\\DATABASE_RESOURCES\\SQLITE\\3_08_06\\new.db");
            c.setAutoCommit(false);
            System.out.println("Opened database successfully");

            stmt = c.createStatement();
            ResultSet rs = stmt.executeQuery( "SELECT * FROM test2;" );
            while ( rs.next() ) {
                System.out.println("Test success : "+ rs.getInt("col1"));
            }
            rs.close();
            stmt.close();
            c.close();
        } catch ( Exception e ) {
            System.err.println( e.getClass().getName() + ": " + e.getMessage() );
            System.exit(0);
        }
        System.out.println("Operation done successfully");
    }


    private static void connectTest() {
        try {
            Class.forName("org.sqlite.JDBC");
            String dbURL = "jdbc:sqlite:new.db";
            Connection conn = DriverManager.getConnection(dbURL);
            if (conn != null) {
                System.out.println("Connected to the database");
                DatabaseMetaData dm = (DatabaseMetaData) conn.getMetaData();
                System.out.println("Driver name: " + dm.getDriverName());
                System.out.println("Driver version: " + dm.getDriverVersion());
                System.out.println("Product name: " + dm.getDatabaseProductName());
                System.out.println("Product version: " + dm.getDatabaseProductVersion());
                conn.close();
            }
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }

    private void select() {
        Connection c = null;
        Statement stmt = null;
        try {
            Class.forName("org.sqlite.JDBC");
            c = DriverManager.getConnection("jdbc:sqlite:new.db");
            c.setAutoCommit(false);
            System.out.println("Opened database successfully");

            stmt = c.createStatement();
            ResultSet rs = stmt.executeQuery( "SELECT * FROM COMPANY;" );
            while ( rs.next() ) {
                int id = rs.getInt("id");
                String  name = rs.getString("name");
                int age  = rs.getInt("age");
                String  address = rs.getString("address");
                float salary = rs.getFloat("salary");
                System.out.println( "ID = " + id );
                System.out.println( "NAME = " + name );
                System.out.println( "AGE = " + age );
                System.out.println( "ADDRESS = " + address );
                System.out.println( "SALARY = " + salary );
                System.out.println("Test success");
            }
            rs.close();
            stmt.close();
            c.close();
        } catch ( Exception e ) {
            System.err.println( e.getClass().getName() + ": " + e.getMessage() );
            System.exit(0);
        }
        System.out.println("Operation done successfully");
    }

    private void createTable() {
        Connection c = null;
        Statement stmt = null;
        try {
            Class.forName("org.sqlite.JDBC");
            c = DriverManager.getConnection("jdbc:sqlite:new.db");
            System.out.println("Opened database successfully");

            stmt = c.createStatement();
            String sql = "CREATE TABLE COMPANY " +
                    "(ID INT PRIMARY KEY     NOT NULL," +
                    " NAME           TEXT    NOT NULL, " +
                    " AGE            INT     NOT NULL, " +
                    " ADDRESS        CHAR(50), " +
                    " SALARY         REAL)";
            stmt.executeUpdate(sql);
            stmt.close();
            c.close();
        } catch ( Exception e ) {
            System.err.println( e.getClass().getName() + ": " + e.getMessage() );
            System.exit(0);
        }
        System.out.println("Table created successfully");
    }

    private void insertSomeData() {
        Connection c = null;
        Statement stmt = null;
        try {
            Class.forName("org.sqlite.JDBC");
            c = DriverManager.getConnection("jdbc:sqlite:new.db");
            c.setAutoCommit(false);
            System.out.println("Opened database successfully");

            stmt = c.createStatement();
            String sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) " +
                    "VALUES (1, 'Paul', 32, 'California', 20000.00 );";
            stmt.executeUpdate(sql);

            sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) " +
                    "VALUES (2, 'Allen', 25, 'Texas', 15000.00 );";
            stmt.executeUpdate(sql);

            sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) " +
                    "VALUES (3, 'Teddy', 23, 'Norway', 20000.00 );";
            stmt.executeUpdate(sql);

            sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) " +
                    "VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 );";
            stmt.executeUpdate(sql);

            stmt.close();
            c.commit();
            c.close();
        } catch ( Exception e ) {
            System.err.println( e.getClass().getName() + ": " + e.getMessage() );
            System.exit(0);
        }
        System.out.println("Records created successfully");
    }
}

Windows SQLite Installation

Install/Run SQLite:
   1. Download SQLite: To download SQLite visit this page : http://www.sqlite.org/download.html
   2. Unpack SQLite
   3. Install SQLite: Now double click on the sqlite.exe file to install SQLite.
   4. Test SQLite:T o test SQLite open up a command prompt window and type 'sqlite3'. To get some help with SQLite type '.help' and to close sqlite3 type '.quit'
 
Create a Test SQLite Database:
    1.  Create SQLite Test Database :
        sqlite3 sqlite.db
       
    2. Create a SQLite Table :
        sqlite3 sqlite.db "create table tb1 (tb1key INTEGER PRIMARY KEY,data TEXT,num double,timeEnter DATE);"

    3. Add Data Into Test Database :
        sqlite3 sqlite.db "insert into tb1 (data,num) values ('Test data',9);"
        sqlite3 sqlite.db "insert into tb1 (data,num) values ('More test data',8);"
        sqlite3 sqlite.db "insert into tb1 (data,num) values ('Third set of data',7);"
       
    4. View Test SQLite Data :
        sqlite3 sqlite.db "select * from tb1";


You may find a GUI Tool to control database
    1. sqlitestudio.2.1.5
    2. sqlitebrowser-3.3.1-win32
    3. sqliteadmin