前一阵子做了一个小项目,关于android的,想记录一下学到的一些知识,做成一个小系列吧,算是对自己这一个多月来的见证。首先说明,这些知识也都是从网上各处学习来的,我自己做了一些小整理。
1.SQLite数据库
之前用的数据库是MySQL和SQLServer,还用过oracle,虽然不是很精通,这次第一次接触SQLite,感觉用起来很方便,直接在android项目里写一个DBHelper类来继承SQLiteOpenHelper就行。但是有些功能还是有局限性,在定义数据类型的时候,string就不对,而text就对,还有无法写double等类型,虽然说会自动转换,个人感觉还是会有些不方便。
public class DBHelper extends SQLiteOpenHelper {
private static DBHelper dbHelper = null;
private final static String DATABASE_NAME="car.db";
private final static int DATABASE_VERSION=1;
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
public static DBHelper getDBHelper(Context context){
if(dbHelper==null){
dbHelper = new DBHelper(context);
}
return dbHelper;
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("create table user(id text primary key,realname text,password text,age integer,sex text,phonenum integer)");
db.execSQL("insert into user(id,realname,password,age,sex,phonenum)values('user','users','user',18,'female',123)");
db.execSQL("create table car(_id text ,carbrand text,carsign text,carmodel text,carnumber text primary key,enginenum text,bodylevel text,mileage integer,gasoline integer,engineperfor text,transperfor text,carlight text,foregin key _id references user(id))");
db.execSQL("insert into car(_id,carbrand,carsign,carmodel,carnumber,enginenum,bodylevel,mileage,gasoline,engineperfor,transperfor,carlight)values('user','auto','sigequan','hao','lyc310','chris826','sixseat',12,10,'异常','异常','坏')");
db.execSQL("create table fuel(username text,date text,gasstation text,filltype text,gaslitre integer)");
db.execSQL("insert into fuel(username,date,gasstation,filltype,gaslitre)values('user','20160601','zhongguoshihua','95',50)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
这是我项目里的代码,很简单,只是建了一个名为car的数据库,还有user、car、fuel三个表,并插入数据。在SQLite中实现增删改查也很简单,这是另一个类里实现的方法。
//查询用户名和密码
public boolean login(String id,String password){
SQLiteDatabase sdb= dbHelper.getReadableDatabase();
String sql="select * from user where id=? and password=?";
Cursor cursor = sdb.rawQuery(sql, new String[]{id,password});
if(cursor.moveToFirst()==true){
cursor.close();
return true;
}
return false;
}
//注册用(增加操作)
public boolean register(User user,String _id){
SQLiteDatabase sdb = dbHelper.getReadableDatabase();
String str = "select id from user where id = ?";
Cursor cursor = sdb.rawQuery(str, new String[]{_id});
if(cursor.moveToFirst()!=true){
String sql ="insert into user(id,realname,password,age,sex,phonenum) values(?,?,?,?,?,?)";
Object obj[]={user.getId(),user.getRealname(),user.getPassword(),user.getAge(),user.getSex()};
sdb.execSQL(sql,obj);
return true;
}else{
return false;
}