这里有两个类一个创建数据库连接,另一个类在数据库中插入一个用户(使用用户类对象)
public class UserDataHelper extends SQLiteOpenHelper {
public UserDataHelper(Context context, String name, CursorFactory factory,
int version) {
super(context, name, factory, version);
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase database) {
// TODO Auto-generated method stub
database.execSQL(UserMataData.sql);
}
@Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
}
}
上面的类创建数据库
public class UserDataSource {
private SQLiteDatabase userDataBase;
private UserDataHelper userDataHelper;
public UserDataSource(Context context) {
super();
userDataHelper = new UserDataHelper(context, UserMataData.DataBaseName, null, UserMataData.DataBaseVersion);
}
public void openDataBase()
{
userDataBase = userDataHelper.getReadableDatabase();
}
public void closeDataBase()
{
userDataHelper.close();
}
public boolean addUser (User user)
{
ContentValues cv = new ContentValues();
cv.put(UserMataData.Name, user.getName());
cv.put(UserMataData.University, user.getUniversity());
long insert = userDataBase.insert(UserMataData.TableName, null, cv);
if( insert != -1)
return true;
return false;
}
public Cursor getAllUsers()
{
return userDataBase.query(UserMataData.TableName, null, null, null, null, null, null);
}
}
注意用户对象只是用户类的一个对象,您可以简单地将其替换为您想要添加到数据库中的任何其他内容并相应地更改 ContentValues