Android working with database

SQLiteDatabase db;

String[] arg={“0″},col;
String str=”select*from maintable where SNo >?”;

 try
{

// creating a database

      db=SQLiteDatabase.openDatabase(“data/data/android.org/we.db”,null,SQLiteDatabase.CREATE_IF_NECESSARY);

// you must be using different path name in my case it is android.org and data base name is we.db

      db.beginTransaction();

// creating a table

      db.execSQL(“create table maintable(SNo integer PRIMARY KEY autoincrement,TruckNo integer,ChallanNo integer,” +                                                “,TransCode integer,TransName text);”);

// inserting the values

db.execSQL(“insert into maintable(TruckNo,ChallanNo,TransCode,TransName)” +
“values(“+String.valueOf(truck_no.getText())+”,”+String.valueOf(challan_no.getText())+                            “,”+String.valueOf(trans_code.getText())+”,’ “+trans_name.getText()+” ‘);”);

// Care should be taken while inserting a text value the value must be enclosed within ‘ ‘.

//Rertriving the data

 c=db.rawQuery(str,arg);

int n=c.getColumnIndex(“SNo”); //sno,truckno and transname are columns in the table
int m=c.getColumnIndex(“TruckNo”);
int tn=c.getColumnIndex(“TransName”);
int j=0,i=0;
while(c.moveToNext())
{

      col[j++]=Integer.toString(c.getInt(n));
TextView.append(col[i++]);

      col[j++]=Integer.toString(c.getInt(m));

      TextView.append(col[i++]);

      col[j++]=c.getString(tn);

      TextView.append(col[i++]);

}

db.endTransaction();

}
catch(SQLException e)
{
e.printStackTrace();
}

Note: Whenever the application runs a new database is created

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s