package com.example.sql; import android.os.Bundle; import android.app.Activity; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.graphics.Color; import android.view.Menu; import android.widget.TextView; public class MainActivity extends Activity { private TextView tv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); DBHelper db=new DBHelper(this); tv=(TextView)findViewById(R.id.tv); tv.setBackgroundColor(Color.RED); db.clear(); //db.insert(); //String str=db.query(0); //System.out.println(str); //db.insert(); db.insert1(3,"cmaker"); String str=db.query(0); tv.setText(str); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } } class DBHelper extends SQLiteOpenHelper { private static final String CREATE_TABLE_SQL="create table TempTb1(_id integer,name text)"; private SQLiteDatabase db; DBHelper(Context context) { super(context,"test.db",null,2); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(CREATE_TABLE_SQL); } @Override public void onUpgrade(SQLiteDatabase db,int OldVersion,int NewVersion) { } public void insert() { String sql="insert into TempTb1(_id,name)values(1,'amaker')"; getWritableDatabase().execSQL(sql); } public void insert1(int id,String name) { //String sql="insert into TempTb1(_id,name)values(2,'bmaker')"; //getWritableDatabase().execSQL(sql); getWritableDatabase().execSQL("insert into TempTb1(_id,name)values(?,?)",new Object[]{id,name}); } public String query(int index) { SQLiteDatabase db=this.getWritableDatabase(); Cursor cur=db.query("TempTb1",null,null,null,null,null,null); if(cur.moveToFirst())//note { cur.move(index); int id=cur.getInt(0); String name=cur.getString(1); String str=id+":"+name; //System.out.println(id+":"+name); db.close();//note return str; } return "Fail to find any item"; } public void clear() { SQLiteDatabase db=this.getWritableDatabase(); db.execSQL("delete from TempTb1"); } }