public class DatabaseHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION=1;
private static final String DATABASE_NAME="Original";
private static final String TABLE_NAME="Register";
private static final String COLUMN_ID="id";
private static final String COLUMN_UNAME="name";
//private static final String COLUMN_EMAIL="email";
private static final String COLUMN_PHONENUMBER="number";
private static final String COLUMN_PASSWORD="password";
public DatabaseHelper(Context mcontext)
{
super(mcontext , DATABASE_NAME , null , DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db)
{
String CREATE_REGISTER_TABLE = " CREATE TABLE " + TABLE_NAME + " ( "
+ COLUMN_ID + " INTEGER PRIMARY KEY, "
+ COLUMN_UNAME + " TEXT, "
+ COLUMN_PHONENUMBER + " TEXT, "
+ COLUMN_PASSWORD + " TEXT " + " ) ";
db.execSQL(CREATE_REGISTER_TABLE);
}
public void insertContact(Original c)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
//String query="SELECT * FROM "+TABLE_NAME;
//Cursor cursor = db.rawQuery(query,null);
// int count=cursor.getCount();
values.put(COLUMN_ID,c.getID());
values.put(COLUMN_UNAME,c.getName());
//values.put(COLUMN_EMAIL,c.getEmail());
values.put(COLUMN_PASSWORD,c.getPassw());
values.put(COLUMN_PHONENUMBER,c.getNumber());
db.insert(TABLE_NAME , null , values);
db.close();
}
public String searchPass(String name)
{
SQLiteDatabase db = this.getReadableDatabase();
String query="SELECT "+COLUMN_UNAME + "AND " +COLUMN_PASSWORD +"FROM "+TABLE_NAME;
Cursor mCursor=db.rawQuery(query , null);
String a,b;
b="not found";
if(mCursor.moveToFirst())
{
do
{
a=mCursor.getString(0);
if(a.equals(name))
{
b=mCursor.getString(1);
break;
}
}
while(mCursor.moveToNext());
}
return b;
}
@Override
public void onUpgrade(SQLiteDatabase db, int i, int i1)
{
String query="DROP TABLE IF EXITS"+TABLE_NAME;
db.execSQL(query);
onCreate(db);
}
}
错误显示在db.insert()
操作中。
主要目的是将详细信息添加到数据库名称Original with table name register
答案 0 :(得分:0)
上面的代码很好,我已经运行了一次(使用单个Original
实例两次以有目的地生成UNIQUE constraint
错误)。但是,如果原始对象的 ID 不唯一,则会失败。你会得到一个错误: -
07-18 06:32:46.208 2819-2819/? E/SQLiteLog: (1555) abort at 11 in [INSERT INTO Register(number,name,password,id) VALUES (?,?,?,?)]: UNIQUE constraint failed: Register.id
07-18 06:32:46.208 2819-2819/? E/SQLiteDatabase: Error inserting number=0312341234 name=Fred password=password id=10
如果这不是错误,那么可能是因为您更改了表的结构(例如添加(最有可能)/删除的列)而没有删除数据库(删除应用程序的数据或卸载应用程序)。这是人们常犯的错误,因为他们没有意识到只在创建数据库时自动调用onCreate
方法。
我怀疑后者因为有迹象表明您已根据注释掉的行//values.put(COLUMN_EMAIL,c.getEmail());
P.S。您应该在返回之前关闭searchPass
方法中的光标,例如代码mCursor.close();
如果上述问题存在,那么您应该编辑您的问题并包含详细说明错误的日志/堆栈跟踪,也可能包括调用活动中的代码,例如: (我使用的代码): -
Original ori = new Original(10l,"Fred","password","fred@email.com","0312341234");
DatabaseHelper dbhlp = new DatabaseHelper(this);
dbhlp.insertContact(ori);