网课指路 B站大神:(学完必会)Android studio基础,从入门到精通,学完小白也能会_哔哩哔哩_bilibili
package com.example.databasetest;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
private MyDatabaseHelper dbHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button)(findViewById(R.id.btn));
Button btn2 = (Button)(findViewById(R.id.btn2));
Button btn3= (Button)(findViewById(R.id.btn3));
Button btn4= (Button)(findViewById(R.id.btn4));
Button btn5= (Button)(findViewById(R.id.btn5));
dbHelper = new MyDatabaseHelper(this,"zhangke.dp",null,1);
btn3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SQLiteDatabase db = dbHelper.getWritableDatabase();//读取
ContentValues values = new ContentValues();//开始组装第一条记录
values.put("name","ZK");
db.update("people",values,"name = ?",new String[]{"zhangke"});
}
});
btn5.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SQLiteDatabase db = dbHelper.getWritableDatabase();//读取
Cursor cursor = db.query("people",null,null,null,null,null,null);
if(cursor.moveToFirst()){
do{
String name = cursor.getString(cursor.getColumnIndex("name"));
int id = cursor.getInt(cursor.getColumnIndex("id"));
Log.d("MainActivity","name"+name);
Log.d("MainActivity","id"+id);
}while (cursor.moveToNext());
}
}
});
btn4.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SQLiteDatabase db = dbHelper.getWritableDatabase();//读取
db.delete("people","age > ?",new String[]{"23"});
}
});
btn2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SQLiteDatabase db = dbHelper.getWritableDatabase();//读取
ContentValues values = new ContentValues();//开始组装第一条记录
values.put("name","zhangke");
values.put("sex","male");
values.put("age",25);
values.put("weight",74.7);
db.insert("people",null,values);//输入第一条数据
values.clear();
values.put("name","TJW");
values.put("sex","female");
values.put("age",22);
values.put("weight",48);
db.insert("people",null,values);//输入第二条数据
values.clear();
}
});
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dbHelper.getWritableDatabase();
}//创建
});
}
}
|