android中SQLite数据库的基本操作以及重要方法介绍

例子挺简单,不废话,贴代码

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		// 创建数据库,一个应用只能有一个数据库
		SQLiteDatabase db = openOrCreateDatabase("user.db", MODE_PRIVATE, null);
		// 创建表
		db.execSQL("create table if not exists usertb (_id integer primary key autoincrement, name text not null , age integer not null , sex text not null)");
		// 清空表中的所有行 或者 db.delete("usertb", null, null);
		// db.delete("usertb", "_id>?", new String[]{"0"});
		db.delete("usertb", null, null);
		// 插入数据
		ContentValues values = new ContentValues();
		values.put("name", "张三");
		values.put("age", 18);
		values.put("sex", "男");
		db.insert("usertb", null, values);
		values.clear();
		values.put("name", "李四");
		values.put("age", 19);
		values.put("sex", "男");
		db.insert("usertb", null, values);
		values.clear();
		values.put("name", "王五");
		values.put("age", 18);
		values.put("sex", "女");
		db.insert("usertb", null, values);
		values.clear();

		// 更新表里的内容
		values.put("sex", "男");
		db.update("usertb", values, "name like ?", new String[] { "%王%" });
		values.clear();
		// 查询表里的内容
		Cursor cursor = db.query("usertb", null, "_id>?", new String[] { "0" },
				null, null, "_id");
		if (cursor != null) {
			while (cursor.moveToNext()) {
				String[] columnNames = cursor.getColumnNames();
				for (String columnName : columnNames) {
					Log.i("Main",
							cursor.getString(cursor.getColumnIndex(columnName)));
				}
			}
			cursor.close();
		}
		db.close();

//		SQLiteDatabase db = openOrCreateDatabase("user.db", MODE_PRIVATE, null);
//		db.execSQL("create table if not exists usertb (_id integer primary key autoincrement, name text not null , age integer not null , sex text not null )");
//
//		db.execSQL("insert into usertb(name,sex,age) values('张三','女',18)");
//		db.execSQL("insert into usertb(name,sex,age) values('李四','女',19)");
//		db.execSQL("insert into usertb(name,sex,age) values('王五','男',20)");
//
//		Cursor c = db.rawQuery("select * from usertb", null);
//		if (c != null) {
//			while (c.moveToNext()) {
//				Log.i("info", "_id:" + c.getInt(c.getColumnIndex("_id")));
//				Log.i("info", "name:" + c.getString(c.getColumnIndex("name")));
//				Log.i("info", "age:" + c.getInt(c.getColumnIndex("age")));
//				Log.i("info", "sex:" + c.getString(c.getColumnIndex("sex")));
//				Log.i("info", "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
//			}
//			c.close();
//		}
//		db.close();
	}
}


上面的代码简单介绍了操作SQLite的方法,以及两种增删改查表的方法(官方推荐第一种方法,即未被注释的部分)。接下来介绍代码里面使用的关键方法:

1.openOrCreateDatabase("user.db", MODE_PRIVATE, null);  创建一个名为user的数据库

方法原型:public SQLiteDatabase openOrCreateDatabase(String name, int mode, CursorFactory factory)

很明显该方法返回的是一个SQLiteDatabase 对象,参数:

name The name (unique in the application package) of the database. 要创建的数据库名
mode Operating mode. Use 0 or MODE_PRIVATE for the default operation, MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE to control permissions. Use MODE_ENABLE_WRITE_AHEAD_LOGGING to enable write-ahead logging by default.
factory An optional factory class that is called to instantiate a cursor when query is called

2.db.execSQL('"")

方法原型:public void execSQL (String sql)

参数:sqlthe SQL statement to be executed. Multiple statements separated by semicolons are not supported.

3.db.insert("usertb", null, values);

方法原型:public long insert (String table, String nullColumnHack, ContentValues values)

Parameters:
table the table to insert the row into
nullColumnHack optional; may be null. SQL doesn't allow inserting a completely empty row without naming at least one column name. If your provided values is empty, no column names are known and an empty row can't be inserted. If not set to null, the nullColumnHack parameter provides the name of nullable column name to explicitly insert a NULL into in the case where your values is empty.
values this map contains the initial column values for the row. The keys should be the column names and the values the column values
Returns:
the row ID of the newly inserted row, or -1 if an error occurred
4.db.delete("usertb", null, null);

方法原型:public int delete (String table, String whereClause, String[] whereArgs)

Parameters
tablethe table to delete from
whereClausethe optional WHERE clause to apply when deleting. Passing null will delete all rows.
whereArgsYou may include ?s in the where clause, which will be replaced by the values from whereArgs. The values will be bound as Strings.
Returns
  • the number of rows affected if a whereClause is passed in, 0 otherwise. To remove all rows and get a count pass "1" as the whereClause. 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android 创建 SQLite 数据库有以下几个步骤: 1. 创建一个继承自 `SQLiteOpenHelper` 类的帮助类,该类用于管理数据库的创建和版本升级。 ```java public class DBHelper extends SQLiteOpenHelper { private static final String DATABASE_NAME = "mydb.db"; private static final int DATABASE_VERSION = 1; public DBHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { // 创建表格等初始化操作 } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // 数据库版本升级时的操作 } } ``` 2. 在帮助类的 `onCreate()` 方法创建表格,并进行必要的初始化操作。 ```java @Override public void onCreate(SQLiteDatabase db) { String sql = "CREATE TABLE IF NOT EXISTS student(" + "id INTEGER PRIMARY KEY AUTOINCREMENT," + "name TEXT," + "age INTEGER" + ")"; db.execSQL(sql); } ``` 3. 在需要创建数据库的地方实例化帮助类,并调用 `getWritableDatabase()` 或 `getReadableDatabase()` 方法来获取可读写或只读的数据库对象。 ```java DBHelper dbHelper = new DBHelper(context); SQLiteDatabase db = dbHelper.getWritableDatabase(); ``` 4. 在获取到数据库对象后,可以通过 `execSQL()` 方法执行 SQL 语句来进行数据库操作。 ```java String sql = "INSERT INTO student(name, age) VALUES('Tom', 18)"; db.execSQL(sql); ``` 以上就是在 Android 创建 SQLite 数据库基本步骤。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值