Android Studio建立一个Sql数据库,并且实现增删改查功能的代码
时间: 2023-11-11 08:11:31 浏览: 164
好的,以下是在Android Studio中建立一个Sql数据库,并实现增删改查功能的代码:
1. 在Android Studio中创建一个新项目,并在gradle文件中添加sqlite依赖:
```
implementation 'androidx.sqlite:sqlite:2.1.0'
implementation 'androidx.sqlite:sqlite-ktx:2.1.0'
```
2. 在项目中创建一个DatabaseHelper类,该类继承自SQLiteOpenHelper类,并重写onCreate()和onUpgrade()方法:
```java
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "mydatabase.db";
private static final int DATABASE_VERSION = 1;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String sql = "CREATE TABLE mytable (_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER);";
db.execSQL(sql);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS mytable");
onCreate(db);
}
}
```
3. 在Activity中使用DatabaseHelper类创建数据库,并实现增删改查功能:
```java
public class MainActivity extends AppCompatActivity {
private DatabaseHelper databaseHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
databaseHelper = new DatabaseHelper(this);
SQLiteDatabase db = databaseHelper.getWritableDatabase();
// 插入数据
ContentValues values = new ContentValues();
values.put("name", "张三");
values.put("age", 20);
db.insert("mytable", null, values);
// 查询数据
Cursor cursor = db.query("mytable", null, null, null, null, null, null);
while (cursor.moveToNext()) {
int id = cursor.getInt(cursor.getColumnIndex("_id"));
String name = cursor.getString(cursor.getColumnIndex("name"));
int age = cursor.getInt(cursor.getColumnIndex("age"));
Log.d("MainActivity", "id:" + id + ", name:" + name + ", age:" + age);
}
cursor.close();
// 更新数据
ContentValues updateValues = new ContentValues();
updateValues.put("age", 21);
db.update("mytable", updateValues, "name=?", new String[]{"张三"});
// 删除数据
db.delete("mytable", "name=?", new String[]{"张三"});
db.close();
}
}
```
这样,就可以在Android Studio中建立一个Sql数据库,并实现增删改查功能了。
阅读全文