@Yano
2016-03-21T09:22:02.000000Z
字数 2331
阅读 2035
Android
实现数据库基本的增删改查
。
MainActivity:
public class MainActivity extends Activity {
private Button button1, button2, button3, button4;
private static MySqlHelper mySqlHelper;
private static SQLiteDatabase db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mySqlHelper = new MySqlHelper(MainActivity.this, "student_inf.db",
null, 1);
db = mySqlHelper.getWritableDatabase();
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
button3 = (Button) findViewById(R.id.button3);
button4 = (Button) findViewById(R.id.button4);
// 添加数据
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 加入2个数据
ContentValues values = new ContentValues();
values.put("name", "stu01");
values.put("password", "abc");
db.insert("student", null, values);
ContentValues values2 = new ContentValues();
values2.put("name", "stu02");
values2.put("password", "def");
db.insert("student", null, values2);
query();
}
});
// 删除数据
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Cursor cursor = db.rawQuery(
"delete from student where name = '" + "stu01" + "'",
null);
cursor.moveToNext();
query();
}
});
// 修改数据
button3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ContentValues values = new ContentValues();
values.put("name", "stu03");
values.put("password", "hig");
db.update("student", values, "name=?", new String[] { "stu01" });
query();
}
});
// 查询数据
button4.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
query();
}
});
}
// 打印数据库中所有的name
private static void query() {
Cursor cursor = db.rawQuery("select * from student", null);
System.out.println("打印数据库中所有的name");
while (cursor.moveToNext()) {
System.out.println(cursor.getString(1));
}
cursor.close();
}
}
MySqlHelper:创建数据库表 student,其中包括 name
和password
两列。注意 execSQL 语句的格式,结尾是有个括号的!
public class MySqlHelper extends SQLiteOpenHelper {
public MySqlHelper(Context context, String name, CursorFactory factory,
int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
// 创建数据库表 student
db.execSQL("create table student(_id integer primary key autoincrement,"
+ "name varchar(20)," + "password varchar(20))");
System.out.println("onCreate 被调用");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
System.out.println("onUpgrade 被调用" + oldVersion + "--" + newVersion);
}
}