mysql插入数据,根据相关字段判断这条数据是否存在,存在就不插入,不存在就插入
简单写一个Android MySQL数据库管理帮助类,代码质量有待提升。
public class MySQLiteOpenHelper extends SQLiteOpenHelper {private Context mContext;private static final String BOOK_TABLE = "Book";private static final String TABLE_NAME = "BookStre.db";private static final int TABLE_VERSION = 1;public static final String CREATE_BOOK = "create table Book("+ "id integer primary key autoincrement,"+ "author text,"+ "price real,"+ "pages integer,"+ "name text)";public MySQLiteOpenHelper(Context context) {super(context, TABLE_NAME, null, TABLE_VERSION);mContext = context;}@Overridepublic void onCreate(SQLiteDatabase db) {db.execSQL(CREATE_BOOK);Toast.makeText(mContext, "Create succeeded!", Toast.LENGTH_SHORT).show();}@Overridepublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}/**插入与修改*(根据author字段判断该数据是否存在,*如数据不存在则插入该数据,*已存在则进行修改数据)*/public void setInsert(BookBean bookBean) {SQLiteDatabase db = this.getWritableDatabase();Cursor query = db.query(BOOK_TABLE, new String[]{"author"}, "author=?",new String[]{bookBean.getAuthor()}, null, null, null);int count = query.getCount();if (count == 0) {//数据不存在则插入ContentValues values = new ContentValues();values.put("name", bookBean.getName());values.put("author", bookBean.getAuthor());values.put("pages", bookBean.getPages());values.put("price", bookBean.getPrice());db.insert(BOOK_TABLE, null, values);} else {//数据存在则更新修改ContentValues values = new ContentValues();values.put("name", bookBean.getName());values.put("author", bookBean.getAuthor());values.put("pages", bookBean.getPages());values.put("price", bookBean.getPrice());db.update(BOOK_TABLE, values, "id=?", new String[]{String.valueOf(bookBean.getId())});}db.close();}//删除(根据id删除数据)public void onDelete(BookBean bookBean) {SQLiteDatabase db = this.getWritableDatabase();db.delete(BOOK_TABLE, "id=?", new String[]{String.valueOf(bookBean.getId())});}}