1. 数据库DBHelper extends SQLiteOpenHelper
import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class DBHelper extends SQLiteOpenHelper { private static final String DB_NAME = "zigbree.db"; private static final String TBL_NAME = "Zigbree"; private static final String CREATE_TBL = " create table " + " Zigbree( _id integer primary key autoincrement,room text,light text) "; //此处必须将id 主键写成 _id //写成_id SimpleCursorAdapter 报错! // ERROR/AndroidRuntime(232): java.lang.RuntimeException: Unable to start activity //ComponentInfo{com.nec.android.necsthz/com.nec.android.necsthz.QueryActivity}: //java.lang.IllegalArgumentException: column '_id' does not exist private SQLiteDatabase db =null; public DBHelper(Context context) { super(context, DB_NAME, null, 1); } @Override public void onCreate(SQLiteDatabase db) { this.db = db; db.execSQL(CREATE_TBL); } public void insert(ContentValues values) { SQLiteDatabase db = getWritableDatabase(); db.insert(TBL_NAME, null, values); db.close(); } public Cursor query() { SQLiteDatabase db = getWritableDatabase(); Cursor c = db.query(TBL_NAME, null, null, null, null, null, null); return c; } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } }
2.Activity 类
/** * @author 2172980000522 * */ public class RoomLightSet extends Activity { private EditText et1, et2; private Button b1; /* (non-Javadoc) * @see android.app.Activity#onCreate(android.os.Bundle) */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.roomlightset); this.setTitle("哥是一个测试"); et1 = (EditText) findViewById(R.id.room); et2 = (EditText) findViewById(R.id.light); b1 = (Button) findViewById(R.id.comfirm); b1.setOnClickListener(new OnClickListener() { public void onClick(View v) { String name = et1.getText().toString(); String url = et2.getText().toString(); ContentValues values = new ContentValues(); values.put("room", name); values.put("light", url); DBHelper helper = new DBHelper(getApplicationContext()); helper.insert(values); System.out.println("insert data to database:"); } }); } }
Cursor ca = contentResolver.query(Browser.BOOKMARKS_URI, null, "1=1", null, null); public void queryColumnName(Cursor cursor){ for(int i=0;i<cursor.getColumnCount();i++){ String columnName = cursor.getColumnName(i); Log.d("TAG","column name:"+columnName); } }
public Cursor select() { SQLiteDatabase db = this.getReadableDatabase(); // Cursor cursor =db.rawQuery("select email_acc from email_table" ,); Cursor cursor = db.query( TABLE_NAME,null, null, null, null, null, null ); // db.close(); // 关闭了就查询不到数据 return cursor; }