SQLite数据库需要继承一个SQLiteOpenHelper然後创出一个构造
package com.example.sqlite.util;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class MySQLHelper extends SQLiteOpenHelper {
private Context context;
public MySQLHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
this.context = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
String sql="create table user(id integer primary key autoincrement,name varchar(30),age integer,address varchar(30))";
db.execSQL(sql);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
(1)定义一个类, 继承SQLiteOpenHelper
(2)重写构造方法 :提供数据库的基本信息 : 上下文对象,数据库名称,Null,数据库的版本号
(3)重写父类的两个方法:
onCreate(): onUpgrade()
package com.example.sqlite.dao;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import com.example.sqlite.bean.User;
import com.example.sqlite.util.MySQLHelper;
public class UserDao {
private static final String TAG = "TAG";
private SQLiteDatabase db;
public UserDao(Context context) {
MySQLHelper user = new MySQLHelper(context, "user.db", null, 1);
db = user.getWritableDatabase();
}
public void insert(User user){
String sql = "insert into user(name,age,address) values(?,?,?)";
// db.execSQL(sql,new Object[]{user.getName(),user.getAge(),user.getAddress()});
ContentValues contentValues = new ContentValues();
contentValues.put(“name”,user.getName());
contentValues.put(“age”,user.getAge());
contentValues.put(“address”,user.getAddress());
db.insert(“user”,null,contentValues);
Log.i(TAG, "insert: "+user.getName()+user.getAge()+user.getAddress());
}
public void update(User user){
String sql = "update user set age=? where id=? ";
db.execSQL(sql,new Object[]{user.getAge(),user.getId()});
}
}