保存数据(3)sqlLite保存数据

前端之家收集整理的这篇文章主要介绍了保存数据(3)sqlLite保存数据前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

1 内存数据库存储


String createTablesql = "CREATE TABLE [t_test] (" + "[id] INTEGER,"
				+ "[name] VARCHAR(20),[memo] TEXT,"
				+ "CONSTRAINT [sqlite_autoindex_t_test_1] PRIMARY KEY ([id]))";
		sqliteDatabase sqliteDatabase = sqliteDatabase.create(null);
		sqliteDatabase.execsql(createTablesql);
		String insertsql = "insert into t_test(id,name) values(?,?)";
		sqliteDatabase.execsql(insertsql,new Object[] 
		{ 1,"老毕" });  

		String selectsql = "select name from t_test";
		Cursor cursor = sqliteDatabase.rawQuery(selectsql,null);
		cursor.moveToFirst();
		Toast.makeText(this,cursor.getString(0),Toast.LENGTH_LONG).show();

		sqliteDatabase.close();

2 物理文件数据库存储
String filename = android.os.Environment.getExternalStorageDirectory()
				+ "/sdcard_test.db";
		String createTablesql = "CREATE TABLE [t_test] (" + "[id] INTEGER,"
				+ "CONSTRAINT [sqlite_autoindex_t_test_1] PRIMARY KEY ([id]))";
		File file = new File(filename);
		if (file.exists())
		{
			file.delete();
		}
		sqliteDatabase database = sqliteDatabase.openOrCreateDatabase(filename,null);
		database.execsql(createTablesql);
		ContentValues contentValues = new ContentValues();
		contentValues.put("id",1);
		contentValues.put("name","Mike");
		contentValues.put("memo","Student");
		database.insert("t_test",null,contentValues);
		String insertsql = "insert into t_test(id,name,memo) values(?,?,?)";
		database.execsql(insertsql,new Object[]{2,"John","��ʦ"});

		String selectsql = "select name,memo from t_test where name=?";
		Cursor cursor = database.rawQuery(selectsql,new String[]
		{ "John" });
		cursor.moveToFirst();
		Toast.makeText(this,cursor.getString(0) + "  " + cursor.getString(1),Toast.LENGTH_LONG).show();
		
		database.close();

猜你在找的Sqlite相关文章