记账本开发4
今天连接了数据库。
package com.example.myapp0.service; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class DatabaseHelper extends SQLiteOpenHelper { static String name="user.db"; static int dbVersion=1; public DatabaseHelper(Context context){super(context, name, null, dbVersion);} public void onCreate(SQLiteDatabase db) { String sql="create table user(id integer primary key autoincrement,je varchar(20),name varchar(20),bz varchar(20)
,rq varchar(20))";
db.execSQL(sql);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){} }
package com.example.myapp0.service; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.example.myapp0.User; public class UserService { private DatabaseHelper dbHelper; public UserService(Context context){dbHelper=new DatabaseHelper(context);} public boolean login(String username,String password) { SQLiteDatabase sdb=dbHelper.getReadableDatabase(); String sql="select * from user where rq=?"; Cursor cursor=sdb.rawQuery(sql, new String[]{rq}); if(cursor.moveToFirst()==true) { cursor.close(); return true; } return false; } public boolean register(User user) { SQLiteDatabase sdb=dbHelper.getReadableDatabase(); String sql="insert into user(je,name,bz,rq) values(?,?,?,?)"; Object obj[]={user.getJe(),user.getName(),user.getBz(),user.getRq()};
sdb.execSQL(sql, obj);
return true;
}
}
package com.example.myapp0; import java.io.Serializable; public class User implements Serializable { private int id; private String je; private String name; private String bz; private String rq; public User(){super();} public User(String je,String name, String bz,String rq) { super(); this.je = je; this.rq = rq; this.name = name; this.bz = bz; } public int getId(){return id;} public void setId(int id){this.id = id;} public String getName(){return name;} public void setName(String name){this.name = name;} public String getJe(){return je;} public void setJe(String je){this.je = je;} public String getBz(){return bz;} public void setBz(String bz){this.bz = bz;} public String getRq(){return rq;} public void setRq(String rq){this.rq = rq;} public String toString(){return "User [id=" + id + ", je=" + je + ", name=" + name + ", bz=" + bz + ",rq=" + rq + "]";} }