本文的目的是介绍使用IntraWeb(43)-测试读取SqLite(二)的详细情况,我们将通过专业的研究、有关数据的分析等多种方式,同时也不会遗漏关于android.database.sqlite.S
本文的目的是介绍使用 IntraWeb (43) - 测试读取 SqLite (二)的详细情况,我们将通过专业的研究、有关数据的分析等多种方式,同时也不会遗漏关于android.database.sqlite.SQLiteConstraintException、android.database.sqlite.SQLiteConstraintException的实例源码、Extjs ajax读取 intraweb数据、IntraWeb的知识。
本文目录一览:- 使用 IntraWeb (43) - 测试读取 SqLite (二)
- android.database.sqlite.SQLiteConstraintException
- android.database.sqlite.SQLiteConstraintException的实例源码
- Extjs ajax读取 intraweb数据
- IntraWeb
使用 IntraWeb (43) - 测试读取 SqLite (二)
一般情况下, 数据源相关控件应该有数据模块中统一管理, 这也方便其他窗体调用; UserSessionUnit 就是一个现成的数据模块.
现在把数据源相关控件放在 UserSessionUnit 的窗体上:
FDPhysSQLiteDriverLink1: TFDPhysSQLiteDriverLink;
FDGUIxWaitCursor1: TFDGUIxWaitCursor;
FDConnection1: TFDConnection;
DataSource1: TDataSource;
FDTable1: TFDTable;
并在其 OnCreate 事件中写代码:
procedure TIWUserSession.IWUserSessionBaseCreate(Sender: TObject);
begin
FDTable1.Connection := FDConnection1;
DataSource1.DataSet := FDTable1;
FDConnection1.DriverName := ''SQLite'';
FDConnection1.Params.Add(''Database=FDDemo.sdb'');
FDTable1.TableName := ''Orders'';
FDTable1.Active := True;
end;
主窗体上只留了 IWDBGrid1: TIWDBGrid, 其代码更简单了:
uses ServerController; {为使用 UserSession}
procedure TIWForm1.IWAppFormCreate(Sender: TObject);
begin
IWDBGrid1.DataSource := UserSession.DataSource1;
IWDBGrid1.Align := alClient;
end;
效果图:

android.database.sqlite.SQLiteConstraintException
android.database.sqlite.sqliteConstraintException:
error code 19: constraint Failed
我的应用程序错误,不知道为什么.
当我向我的数据库添加一个新的收件箱项时,会发生这种情况.
这是我的收件箱表的Create语句:
CREATE TABLE inBox (uid text,title text,sender text,timeRecieved text,PRIMARY KEY(uid));
使用这些静态最终字符串实现;
public static final String LABEL_INBox_UID = "uid"; public static final String LABEL_INBox_TITLE = "title"; public static final String LABEL_INBox_SENDER = "sender"; public static final String LABEL_INBox_TIME_RECIEVED = "timeRecieved"; public static final int COLUMN_INBox_UID = 0; public static final int COLUMN_INBox_TITLE = 1; public static final int COLUMN_INBox_SENDER= 2; public static final int COLUMN_INBox_TIME_RECIEVED = 3; public static final String TABLE_NAME_INBox = "inBox"; public static final String TABLE_CREATE_INBox = "CREATE TABLE " + TABLE_NAME_INBox + " (" + LABEL_INBox_UID + " text," + LABEL_INBox_TITLE + " text," + LABEL_INBox_SENDER + " text," + LABEL_INBox_TIME_RECIEVED + " text," + "PRIMARY KEY(" + LABEL_INBox_UID + ")" + ");";
以下是获取收件箱项并将其放入contentValues()的方法
@Override protected void insertItem(InBoxListItem object,String table) { InBoxListItem item = object; inBoxItemValue = new ContentValues(); inBoxItemValue.put(LABEL_INBox_UID,item.getUid()); Log.d(TAG,"item.getUid() " + item.getUid()); inBoxItemValue.put(LABEL_INBox_TIME_RECIEVED,item.getTimeRecieved()); Log.d(TAG,"item.getTimeRecieved() " + item.getTimeRecieved()); inBoxItemValue.put(LABEL_INBox_TITLE,item.getTitle()); Log.d(TAG,"item.getTitle() " + item.getTitle()); inBoxItemValue.put(LABEL_INBox_SENDER,item.getSender()); Log.d(TAG,"item.getSender() " + item.getSender()); Log.d(TAG,"TABLE_CREATE_EVENTS =" + TABLE_CREATE_EVENTS); Log.d(TAG,"TABLE_CREATE_INBox =" + TABLE_CREATE_INBox); Log.d(TAG,"TABLE_CREATE_CONTACTS =" + TABLE_CREATE_CONTACTS); database().insert(TABLE_NAME_INBox,null,inBoxItemValue); Log.d(TAG,"database().insert(TABLE_NAME_INBox,inBoxItemValue);"); }
O和这里是完整的异常消息:
11-22 12:24:39.606:
ERROR/Database(773): Error inserting
sender=Mit Technology Review
uid=663b074a-16c8-46fb-a420-e0ebf716e212
title=Emerging Technologies Friday
Update (11/19/2010)
timeRecieved=2010-11-19T06:02:36.000Z
11-22 12:24:39.606:
ERROR/Database(773):
android.database.sqlite.sqliteConstraintException:
error code 19: constraint Failed 11-22
12:24:39.606: ERROR/Database(773):
at
android.database.sqlite.sqliteStatement.native_execute(Native
Method) 11-22 12:24:39.606:
ERROR/Database(773): at
android.database.sqlite.sqliteStatement.execute(sqliteStatement.java:55)
11-22 12:24:39.606:
ERROR/Database(773): at
android.database.sqlite.sqliteDatabase.insertWithOnConflict(sqliteDatabase.java:1549)
11-22 12:24:39.606:
ERROR/Database(773): at
android.database.sqlite.sqliteDatabase.insert(sqliteDatabase.java:1410)
11-22 12:24:39.606:
ERROR/Database(773): at
com.kc.database.InBoxDbWrapper.insertItem(InBoxDbWrapper.java:44)
11-22 12:24:39.606:
ERROR/Database(773): at
com.kc.database.InBoxDbWrapper.insertItem(InBoxDbWrapper.java:1)
11-22 12:24:39.606:
ERROR/Database(773): at
com.kc.database.DbWrapper.insertAllItemsToDb(DbWrapper.java:42)
11-22 12:24:39.606:
ERROR/Database(773): at
com.kc.database.InBoxDbWrapper.populateTable(InBoxDbWrapper.java:54)
11-22 12:24:39.606:
ERROR/Database(773): at
com.kc.main.screen.HomeMainScreenOne.loadDataToDb(HomeMainScreenOne.java:225)
11-22 12:24:39.606:
ERROR/Database(773): at
com.kc.main.screen.AbstractMainScreen.onCreate(AbstractMainScreen.java:125)
11-22 12:24:39.606:
ERROR/Database(773): at
com.kc.main.screen.HomeMainScreenOne.onCreate(HomeMainScreenOne.java:51)
11-22 12:24:39.606:
ERROR/Database(773): at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
11-22 12:24:39.606:
ERROR/Database(773): at
android.app.ActivityThread.performlaunchActivity(ActivityThread.java:2627)
11-22 12:24:39.606:
ERROR/Database(773): at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
11-22 12:24:39.606:
ERROR/Database(773): at
android.app.ActivityThread.access$2300(ActivityThread.java:125)
11-22 12:24:39.606:
ERROR/Database(773): at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
11-22 12:24:39.606:
ERROR/Database(773): at
android.os.Handler.dispatchMessage(Handler.java:99)
11-22 12:24:39.606:
ERROR/Database(773): at
android.os.Looper.loop(Looper.java:123)
11-22 12:24:39.606:
ERROR/Database(773): at
android.app.ActivityThread.main(ActivityThread.java:4627)
11-22 12:24:39.606:
ERROR/Database(773): at
java.lang.reflect.Method.invokeNative(Native
Method) 11-22 12:24:39.606:
ERROR/Database(773): at
java.lang.reflect.Method.invoke(Method.java:521)
11-22 12:24:39.606:
ERROR/Database(773): at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
11-22 12:24:39.606:
ERROR/Database(773): at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
11-22 12:24:39.606:
ERROR/Database(773): at
dalvik.system.NativeStart.main(Native
Method)
提前致谢:
编辑:更多信息.我以前创建了一个事件和contactsList表成功,这似乎工作正常.这是下面的代码:
联系方式:
// Variables used to create the events table public static final String TABLE_NAME_CONTACTS = "contactsList"; public static final String LABEL_CONTACTS_UID = "uid"; public static final String LABEL_CONTACTS_FULLNAME = "fullname"; public static final String TABLE_CREATE_CONTACTS = "CREATE TABLE " + TABLE_NAME_CONTACTS + " (" + LABEL_CONTACTS_UID + " text," + LABEL_CONTACTS_FULLNAME + " text," + "PRIMARY KEY(" + LABEL_CONTACTS_UID + ")" + ");"; public static final int COLUMN_CONTACTS_UID = 0; public static final int COLUMN_CONTACTS_FULLNAME = 1; CREATE TABLE contactsList (uid text,fullname text,PRIMARY KEY(uid));
日历活动:
public static final String LABEL_EVENTS_UID = "uid"; public static final String LABEL_EVENTS_TITLE = "title"; public static final String LABEL_EVENTS_LOCATION = "location"; public static final String LABEL_EVENTS_DATE = "date"; public static final String LABEL_EVENTS_TIME = "time"; public static final String LABEL_EVENTS_TIMEZONE = "timezone"; public static final int COLUMN_EVENTS_UID = 0; public static final int COLUMN_EVENTS_TITLE = 1; public static final int COLUMN_EVENTS_LOCATION = 2; public static final int COLUMN_EVENTS_DATE = 3; public static final int COLUMN_EVENTS_TIME = 4; public static final int COLUMN_EVENTS_TIMEZONE = 5; // Variables used to create the events table public static final String TABLE_NAME_EVENTS = "events"; public static final String TABLE_CREATE_EVENTS = "CREATE TABLE " + TABLE_NAME_EVENTS + " (" + LABEL_EVENTS_UID + " text," + LABEL_EVENTS_TITLE + " varchar(30)," + LABEL_EVENTS_LOCATION + " varchar(30)," + LABEL_EVENTS_DATE + " varchar(30)," + LABEL_EVENTS_TIME + " varchar(30)," + LABEL_EVENTS_TIMEZONE + " varchar(30)," + "PRIMARY KEY(" + LABEL_EVENTS_UID + ")" + ");"; CREATE TABLE events (uid text,title varchar(30),location varchar(30),date varchar(30),time varchar(30),timezone varchar(30),PRIMARY KEY(uid));
解决方法
android.database.sqlite.SQLiteConstraintException的实例源码
private static final void readExceptionFromParcel(Parcel reply,String msg,int code) { switch (code) { case 2: throw new IllegalArgumentException(msg); case 3: throw new UnsupportedOperationException(msg); case 4: throw new sqliteAbortException(msg); case 5: throw new sqliteConstraintException(msg); case 6: throw new sqliteDatabaseCorruptException(msg); case 7: throw new sqliteFullException(msg); case 8: throw new sqlitediskIOException(msg); case 9: throw new sqliteException(msg); case 11: throw new OperationCanceledException(msg); default: reply.readException(code,msg); } }
@Nullable @Override public Uri insert(@NonNull Uri uri,ContentValues values) { final sqliteDatabase db = mOpenHelper.getWritableDatabase(); MovieUriEnum matchingUriEnum = mUriMatcher.matchUri(uri); if (matchingUriEnum.table != null) { try { db.insertOrThrow(matchingUriEnum.table,null,values); } catch (sqliteConstraintException e) { throw e; } } switch (matchingUriEnum) { case MOVIES: return Movies.buildMovieUri(values.getAsstring(Movies.MOVIE_ID)); case TVS: return TVs.buildTVUri(values.getAsstring(TVs.TV_ID)); case PERSONS: return Persons.buildPersonUri(values.getAsstring(Persons.PERSON_ID)); default: throw new UnsupportedOperationException("UnkNown insert URI: " + uri); } }
/** * Returns a Task (with Reminder and Attachments) given a taskId * @param taskId The ID of the Task to get. */ public Task getTask(int taskId) throws CouldNotGetDataException,sqliteConstraintException { sqliteDatabase db = mDatabaseHelper.getReadableDatabase(); Cursor cursor = db.query(RemindyContract.TaskTable.TABLE_NAME,RemindyContract.PlaceTable._ID + "=?",new String[]{String.valueOf(taskId)},null); if (cursor.getCount() == 0) throw new CouldNotGetDataException("Specified Task not found in the database. Passed id=" + taskId); if (cursor.getCount() > 1) throw new sqliteConstraintException("Database UNIQUE constraint failure,more than one record found. Passed value=" + taskId); cursor.movetoNext(); Task task = getTaskFromCursor(cursor); task.setAttachments(getAttachmentsOfTask(taskId)); if(task.getReminderType() != ReminderType.NONE) task.setReminder(getReminderOfTask(taskId,task.getReminderType())); return task; }
public synchronized long insertEmoticonBean(EmoticonBean bean,String beanSetName) { sqliteDatabase db = mOpenDbHelper.getWritableDatabase(); long result = -1; if (bean == null || db == null) { return result; } ContentValues values = new ContentValues(); values.put(TableColumns.EmoticonColumns.EVENT_TYPE,bean.getEventType()); values.put(TableColumns.EmoticonColumns.TAG,bean.getTag()); values.put(TableColumns.EmoticonColumns.NAME,bean.getName()); values.put(TableColumns.EmoticonColumns.ICON_URI,bean.getIconUri()); values.put(TableColumns.EmoticonColumns.MSG_URI,bean.getMsgUri()); values.put(TableColumns.EmoticonColumns.EMOTICON_SET_NAME,beanSetName); try { result = db.insert(TABLE_NAME_EMOTICONS,values); } catch (sqliteConstraintException e) { Log.e(TAG,"insert Failed",e); } return result; }
private static final void readExceptionFromParcel(Parcel reply,msg); } }
@Nullable @Override public Uri insert(@NonNull Uri uri,values); } catch (sqliteConstraintException e) { throw e; } } switch (matchingUriEnum) { case MOVIES: return Movies.buildMovieUri(values.getAsstring(Movies.MOVIE_ID)); case TVS: return TVs.buildTVUri(values.getAsstring(TVs.TV_ID)); case PERSONS: return Persons.buildPersonUri(values.getAsstring(Persons.PERSON_ID)); default: throw new UnsupportedOperationException("UnkNown insert URI: " + uri); } }
public void addNewUser() { User person = new User(); person.setFirstname(getData(txtFirstname)); person.setAge(getData(txtAge)); person.setNic(getData(txtNIC)); person.setSurname(getData(txtSurname)); try { long f = user.insert(person); if (f > 0) { showToast("User added"); clearallTextData(); } else { showToast("User not added"); } } catch (sqliteConstraintException e) { showToast("User with the same NFC id Exists"); } }
@MediumTest public void testStatementConstraint() throws Exception { mDatabase.execsql("CREATE TABLE test (num INTEGER NOT NULL);"); sqliteStatement statement = mDatabase.compileStatement("INSERT INTO test (num) VALUES (?)"); // Try to insert NULL,which violates the constraint try { statement.clearBindings(); statement.execute(); fail("expected exception not thrown"); } catch (sqliteConstraintException e) { // expected } // Make sure the statement can still be used statement.bindLong(1,1); statement.execute(); statement.close(); Cursor c = mDatabase.query("test",null); int numCol = c.getColumnIndexOrThrow("num"); c.movetoFirst(); long num = c.getLong(numCol); assertEquals(1,num); c.close(); }
@MediumTest public void testStatementConstraint() throws Exception { mDatabase.execsql("CREATE TABLE test (num INTEGER NOT NULL);"); sqliteStatement statement = mDatabase.compileStatement("INSERT INTO test (num) VALUES (?)"); // Try to insert NULL,num); c.close(); }
public boolean insertAchievementExplorer(final Context preferenceContext,String email,int idAchievement) { try{ setAction(false); AchievementExplorerRequest achievementExplorerRequest = new AchievementExplorerRequest(email,idAchievement); achievementExplorerRequest.requestUpdateAchievements(preferenceContext,new AchievementExplorerRequest.Callback() { @Override public void callbackResponse(boolean response) { setResponse(true); setAction(true); } @Override public void callbackResponse(List<Achievement> achievements) {} }); }catch(sqliteConstraintException exception){ exception.printstacktrace(); } return true; }
public boolean insertExplorerElement(final Context preferenceContext,int idElement,String userImage,String catchDate) { try{ setAction(false); ElementExplorerRequest elementExplorerRequest = new ElementExplorerRequest(email,idElement,userImage,catchDate); elementExplorerRequest.requestUpdateElements(preferenceContext,new ElementExplorerRequest.Callback() { @Override public void callbackResponse(boolean response) { setResponse(true); setAction(true); } MainController mainController = new MainController(); @Override public void callbackResponse(List<Element> elements) {} }); }catch(sqliteConstraintException exception){ throw exception; } return true; }
public static boolean insert(DBHelper dbHelper,NewGankData.Results data) { sqliteDatabase db = dbHelper.getWritableDatabase(); db.beginTransaction(); try { ContentValues values = new ContentValues(); values.put(Constants.DB_ITEM_DESC,data.getDesc()); values.put(Constants.DB_ITEM_TYPE,data.getType()); values.put(Constants.DB_ITEM_URL,data.getUrl()); db.insert(Constants.DB_TABLE_NAME,values); db.setTransactionSuccessful(); return true; } catch (sqliteConstraintException e) { LogUtils.e("DBTools -> insert","insert data error"); return false; } finally { db.endTransaction(); } }
/** * Add a new UserDevice. * * @param userDevice The new UserDevice. */ public void addUserDevice(UserDevice userDevice) throws DatabaseControllerException { try { databaseConnector.executesql("insert into " + DatabaseContract.UserDevice.TABLE_NAME + " (" + DatabaseContract.UserDevice.COLUMN_NAME + "," + DatabaseContract.UserDevice.COLUMN_FINGERPRINT + "," + DatabaseContract.UserDevice.COLUMN_GROUP_ID + ") values (?,?,(" + DatabaseContract.sqlQueries.GROUP_ID_FROM_NAME_sql_QUERY + "))",new String[]{userDevice.getName(),userDevice.getUserdeviceid().getIDString(),userDevice.getInGroup()}); } catch (sqliteConstraintException sqlce) { throw new DatabaseControllerException( "Either the given Group does not exist in the database" + " or a UserDevice already has the given name or fingerprint.",sqlce); } }
/** * Add a new action to the database. * * @param action Action to be added to the database. * @param moduleName Module where the action occurs. * @param timestamp The timestamp of the action. */ public void addHolidayLogEntry(String action,String moduleName,long timestamp) throws UnkNownReferenceException { if (Strings.isNullOrEmpty(moduleName)) { databaseConnector.executesql( "insert into " + DatabaseContract.HolidayLog.TABLE_NAME + " (" + DatabaseContract.HolidayLog.COLUMN_ACTION + "," + DatabaseContract.HolidayLog.COLUMN_TIMESTAMP + ") values (?,?)",new String[]{action,String.valueOf(timestamp)} ); } else { try { databaseConnector.executesql( "insert into " + DatabaseContract.HolidayLog.TABLE_NAME + " (" + DatabaseContract.HolidayLog.COLUMN_ACTION + "," + DatabaseContract.HolidayLog.COLUMN_ELECTRONIC_MODULE_ID + ",(" + DatabaseContract.sqlQueries.MODULE_ID_FROM_NAME_sql_QUERY + "),moduleName,String.valueOf(timestamp)} ); } catch (sqliteConstraintException sqlce) { throw new UnkNownReferenceException("The given module doesn't exist.",sqlce); } } }
/** * Add a new Module. * * @param module Module to add. */ public void addModule(Module module) throws DatabaseControllerException { try { //Notice: Changed order of values to avoid having to concat twice! databaseConnector.executesql("insert into " + DatabaseContract.ElectronicModule.TABLE_NAME + " (" + DatabaseContract.ElectronicModule.COLUMN_GPIO_PIN + "," + DatabaseContract.ElectronicModule.COLUMN_USB_PORT + "," + DatabaseContract.ElectronicModule.COLUMN_WLAN_PORT + "," + DatabaseContract.ElectronicModule.COLUMN_WLAN_USERNAME + "," + DatabaseContract.ElectronicModule.COLUMN_WLAN_PASSWORD + "," + DatabaseContract.ElectronicModule.COLUMN_WLAN_IP + "," + DatabaseContract.ElectronicModule.COLUMN_MODULE_TYPE + "," + DatabaseContract.ElectronicModule.COLUMN_CONNECTOR_TYPE + "," + DatabaseContract.ElectronicModule.COLUMN_SLAVE_ID + "," + DatabaseContract.ElectronicModule.COLUMN_NAME + ") values " + "(?,(" + DatabaseContract.sqlQueries.SLAVE_ID_FROM_FINGERPRINT_sql_QUERY + "),ObjectArrays.concat( createCombinedModulesAccessinformationFromSingle(module.getModuleAccesspoint()),new String[]{module.getModuleType().toString(),module.getModuleAccesspoint().getType(),module.getAtSlave().getIDString(),module.getName()},String.class)); } catch (sqliteConstraintException sqlce) { throw new DatabaseControllerException("The given Slave does not exist in the database" + " or the name is already used by another Module",sqlce); } }
/** * Adds a new Permission to the database. * * @param permission Permission to add. * @param moduleName Module the permission applies for. */ public void addPermission(de.unipassau.isl.evs.ssh.core.sec.Permission permission,String moduleName) throws DatabaseControllerException { try { if (Strings.isNullOrEmpty(moduleName)) { databaseConnector.executesql("insert into " + DatabaseContract.Permission.TABLE_NAME + " (" + DatabaseContract.Permission.COLUMN_NAME + ")" + " values (?)",new String[] { permission.toString() } ); } else { databaseConnector.executesql("insert into " + DatabaseContract.Permission.TABLE_NAME + " (" + DatabaseContract.Permission.COLUMN_NAME + "," + DatabaseContract.Permission.COLUMN_ELECTRONIC_MODULE_ID + ")" + "values (?,(" + DatabaseContract.sqlQueries.MODULE_ID_FROM_NAME_sql_QUERY + "))",new String[] { permission.toString(),moduleName } ); } } catch (sqliteConstraintException sqlce) { throw new DatabaseControllerException("Either the name-module combination is already exists in the database" + " or the given module doesn't exist.",sqlce); } }
@Test public void testOnUpgradeWithColumnChangetoNotNull() throws Exception { getHelperInstance() .getReadableDatabase() .execsql("CREATE TABLE testTable3 (" + " `xx` INTEGER PRIMARY KEY AUTOINCREMENT," + " `str` TEXT," + " `unique` UNIQUE," + " `foreign` INTEGER," + " FOREIGN KEY(`foreign`) REFERENCES test_table(`unique`)" + ");" ); sqliteOperator<TestTable3> operator = sqliteOperator.from(getContext(),TestTable3.class); TestTable3 t = new TestTable3(); operator.save(t).executeBlocking(); operator.delete(t).executeBlocking(); getHelperInstance().onUpgrade(getHelperInstance().getWritableDatabase(),1,2); exception.expect(sqliteConstraintException.class); operator.save(new TestTable3()).executeBlocking(); }
@Test public void testOnUpgradeWithColumnChangetoUnique() throws Exception { getHelperInstance() .getReadableDatabase() .execsql("CREATE TABLE testTable3 (" + " `xx` INTEGER PRIMARY KEY AUTOINCREMENT," + " `unique` TEXT,TestTable3.class); getHelperInstance().onUpgrade(getHelperInstance().getWritableDatabase(),2); exception.expect(sqliteConstraintException.class); TestTable3 t = new TestTable3(); t.str = "not null"; t.unique = "a"; operator.save(t).executeBlocking(); t = new TestTable3(); t.str = "xxx"; t.unique = "a"; operator.save(t).executeBlocking(); }
/** * Inserts a new category into the database. * @param c the current context. * @param name the name of the category */ public static boolean addCategory(Context c,String name) { boolean success = true; DbOpenHelper dbHelper = new DbOpenHelper(c); sqliteDatabase db = dbHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(CategoryEntry.COLUMN_NAME,name.trim()); try { db.insertOrThrow(CategoryEntry.TABLE_NAME,values); } catch (sqliteConstraintException e) { success = false; } db.close(); return success; }
/** * Insert a news Feed into the database * @param newsFeed the news Feed to add to the database * @param category the title of the category * @return true if the news Feed was successfully inserted,false otherwise */ public boolean insertNewsFeed(NewsFeed newsFeed,String category) { sqliteDatabase db = getWritableDatabase(); ContentValues values = new ContentValues(); values.put(DatabaseContract.NewsFeed.COLUMN_NAME_LABEL,newsFeed.getLabel()); values.put(DatabaseContract.NewsFeed.COLUMN_NAME_LINK,newsFeed.getLink()); values.put(DatabaseContract.NewsFeed.COLUMN_NAME_CATEGORY,category); try { db.insertWithOnConflict(DatabaseContract.NewsFeed.TABLE_NAME,values,sqliteDatabase.CONFLICT_ABORT); } catch (sqliteConstraintException e) { Log.d("DB","Conflict on insertion"); return false; } return true; }
/** * Insert a news category into the database * @param newscategory the news category to add to the database * @return true if the news category was successfully inserted,false otherwise */ public boolean insertNewscategory(Newscategory newscategory) { sqliteDatabase db = getWritableDatabase(); ContentValues values = new ContentValues(); values.put(DatabaseContract.Newscategory.COLUMN_NAME_TITLE,newscategory.getTitle()); try { db.insertWithOnConflict(DatabaseContract.Newscategory.TABLE_NAME,sqliteDatabase .CONFLICT_ABORT); } catch (sqliteConstraintException e) { Log.d("DB","Conflict on insertion"); return false; } for (NewsFeed newsFeed : newscategory.getFeeds()) { insertNewsFeed(newsFeed,newscategory.getTitle()); } return true; }
/** * Remove a news category from the database * @param newscategory the news category to remove * @return true if the news category was successfully removed,false otherwise */ public boolean removeNewscategory(Newscategory newscategory) { sqliteDatabase db = getWritableDatabase(); for (NewsFeed newsFeed : newscategory.getFeeds()) { removeNewsFeed(newsFeed.getLabel()); } try { db.delete(DatabaseContract.Newscategory.TABLE_NAME,"title = ?",new String[]{newscategory.getTitle()}); } catch (sqliteConstraintException e) { Log.d("DB","Conflict on deletion"); return false; } return true; }
public void addDataStore(DataStore_Data Data) { sqliteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(KEY_ID,Data.getID()); // Data ID values.put(KEY_DEVID,Data.getDevID()); // Device ID values.put(KEY_ADDRESS,Data.getAddress()); // Data Address values.put(KEY_FUNC,Data.getFunction()); // Data Function values.put(KEY_STATUS,Data.getStatus()); // Data Status values.put(KEY_ACTIV,Data.getisActive()); // Data Active // Inserting Row db.insert(TABLE_DataStoreS,values); try { db.insertOrThrow(TABLE_DataStoreS,"Database insert error try update.."); db.update(TABLE_DataStoreS,KEY_ID + " = ?",new String[]{String.valueOf(Data.getID())}); Log.d(TAG,"Success"); } db.close(); // Closing database connection }
private void insertContentValues(ContentValues cv,FormIndex index) { synchronized(mScrollActions) { try { while ( !mScrollActions.isEmpty() ) { ContentValues scv = mScrollActions.removeFirst(); mDb.insert(DATABASE_TABLE,scv); } if ( cv != null ) { String idx = ""; if ( index != null ) { idx = getXPath(index); } cv.put(QUESTION,idx); mDb.insert(DATABASE_TABLE,cv); } } catch (sqliteConstraintException e) { System.err.println("Error: " + e.getMessage()); } } }
/** * Decide come interpretare gli out e logga */ public void logTypical() { ContentValues values = new ContentValues(); // wrap values from object values.put(SoulissDBOpenHelper.COLUMN_LOG_NODE_ID,getNodeId()); values.put(SoulissDBOpenHelper.COLUMN_LOG_DATE,Calendar.getInstance().getTime().getTime()); values.put(SoulissDBOpenHelper.COLUMN_LOG_SLOT,getSlot()); if (isSensor()) { Log.d(it.angelic.soulissclient.Constants.TAG,getDefaultName() + " saving sensor loggi: " + ((ISoulisstypicalSensor) this).getoutputFloat()); values.put(SoulissDBOpenHelper.COLUMN_LOG_VAL,((ISoulisstypicalSensor) this).getoutputFloat()); } else { Log.d(it.angelic.soulissclient.Constants.TAG,getDefaultName() + " saving loggi: " + getoutput()); values.put(SoulissDBOpenHelper.COLUMN_LOG_VAL,getoutput()); } try { SoulissDBHelper.getDatabase().insert(SoulissDBOpenHelper.TABLE_LOGS,values); } catch (sqliteConstraintException e) { // sensori NaN violano il constraint Log.e(it.angelic.soulissclient.Constants.TAG,"error saving log: " + e); } }
@Override public Uri insert(Uri uri,ContentValues values) { ContentConstants.ProtocolURLs vrUrl = convertURIToProtocolURL(uri); long rowId = -1; switch (vrUrl) { case URLProtocol: rowId = db.getWritableDatabase().insert(Protocol.TABLE_NAME,values); new backupmanager(getContext()).dataChanged(); break; default: throw new sqliteConstraintException("Failed to switch insert protocol " + uri); } // If the insert succeeded,the row ID exists. if (rowId > 0) { // Creates a URI with the note ID pattern and the new row ID appended to it. Uri noteUri = ContentConstants.getUriFor(vrUrl,rowId); // Notifies observers registered against this provider that the data changed. getContext().getContentResolver().notifyChange(noteUri,null); return noteUri; } else { throw new sqliteConstraintException("Failed to insert row into " + uri); } }
private void onsqliteError(sqliteException e) { if ( e instanceof sqliteBindOrColumnIndexOutOfRangeException || e instanceof sqliteConstraintException || e instanceof sqliteDatabaseCorruptException || e instanceof sqliteDatatypeMismatchException ) { // If a migration did not go well,the best we can do is drop the database and re-create // it from scratch. This is hackish but should allow more or less graceful recoveries. TrackHelper.track().event("Office","cache.db.error").name("critical").value(1f).with(tracker); Log.e(TAG,"Critical database error. Droping + Re-creating",e); close(); ctx.deleteDatabase(DB_NAME); } else { // Generic error. Close + re-open Log.e(TAG,"Datable "+e.getClass().getName()+". Closing + re-opening",e); TrackHelper.track().event("Office","cache.db.error").name(e.getClass().getName()).value(1f).with(tracker); close(); } }
@Test(expected = sqliteConstraintException.class) public void throw_sqlite_constraint_exception_when_persist_a_data_element_with_invalid_option_set_foreign_key() { String fakeOptionSetUid = "fake_option_set_uid"; store.insert( UID,CODE,NAME,disPLAY_NAME,date,SHORT_NAME,disPLAY_SHORT_NAME,DESCRIPTION,disPLAY_DESCRIPTION,VALUE_TYPE,ZERO_IS_SIGNIFICANT,AGGREGATION_OPERATOR,FORM_NAME,NUMBER_TYPE,DOMAIN_TYPE,DIMENSION,disPLAY_FORM_NAME,fakeOptionSetUid,null ); }
@Test(expected = sqliteConstraintException.class) public void not_insert_relationship_in_data_base_when_insert_null() { //Insert foreign keys in their respective tables: ContentValues relationshipType = CreateRelationshipTypeUtils.create( RELATIONSHIP_TYPE_ID,RELATIONSHIP_TYPE ); database().insert(RelationshipTypeModel.TABLE,relationshipType); long rowId = store.insert(null,RELATIONSHIP_TYPE); Cursor cursor = database().query(RelationshipModel.TABLE,RELATIONSHIP_PROJECTION,null); assertthat(rowId).isEqualTo(1L); assertthatCursor(cursor).hasRow(null,RELATIONSHIP_TYPE).isExhausted(); }
@Test(expected = sqliteConstraintException.class) public void throw_exception_after_persist_event_with_invalid_program_foreign_key() { eventStore.insert( EVENT_UID,ENROLLMENT_UID,CREATED_AT_CLIENT,LAST_UPDATED_AT_CLIENT,STATUS,LATITUDE,LONGITUDE,WRONG_UID,//supply wrong uid PROGRAM_STAGE,ORGANISATION_UNIT,STATE,ATTRIBUTE_CATEGORY_OPTION_UID,ATTRIBUTE_OPTION_COMBO_UID,TRACKED_ENTITY_INSTANCE ); }
@Test(expected = sqliteConstraintException.class) public void throw_exception_after_persist_event_with_invalid_program_stage_foreign_key() throws ParseException { eventStore.insert( EVENT_UID,PROGRAM,//supply wrong uid ORGANISATION_UNIT,TRACKED_ENTITY_INSTANCE ); }
@Test(expected = sqliteConstraintException.class) public void throw_exception_after_persist_event_with_invalid_organisation_unit_foreign_key() { eventStore.insert( EVENT_UID,PROGRAM_STAGE,//supply wrong uid date,TRACKED_ENTITY_INSTANCE ); }
@Test(expected = sqliteConstraintException.class) public void throw_exception_after_persist_event_with_invalid_enrollment_foreign_key() { eventStore.insert( EVENT_UID,// supply wrong uid date,TRACKED_ENTITY_INSTANCE ); }
@Test(expected = sqliteConstraintException.class) public void throw_sqlite_constraint_exception_when_insert_program_stage_data_element_with_invalid_foreign_key() { String fakeDataElementId = "fake_data_element_id"; store.insert( UID,disPLAY_IN_REPORTS,COmpuLSORY,ALLOW_PROVIDED_ELSEWHERE,SORT_ORDER,ALLOW_FUTURE_DATE,fakeDataElementId,null ); }
@Test(expected = sqliteConstraintException.class) public void throw_sqlite_constraint_exception_when_persist_enrollment_with_invalid_org_unit_foreign_key() { store.insert( UID,//supply wrong uid PROGRAM,FOLLOW_UP,ENROLLMENT_STATUS,TRACKED_ENTITY_INSTANCE,STATE ); }
@Test(expected = sqliteConstraintException.class) public void throw_sqlite_constraint_exception_when_persist_enrollment_with_invalid_program_foreign_key() { store.insert( UID,STATE ); }
@Test(expected = sqliteConstraintException.class) public void throw_sqlite_constraint_exception_persist_enrollment_with_invalid_tracked_entity_instance_foreign_key() { store.insert( UID,//supply wrong uid LATITUDE,STATE ); }
@Test public void testInsertPrimaryKeyConflictCompoundKey() throws Exception { final TestDao dao = getDao(); // create object final Compound orig = new Compound("1","2","orig","orig"); dao.insert(orig); // test PK conflict final Compound conflict = new Compound("1","conflict","conflict"); try { dao.insert(conflict); fail("There should have been a PK conflict"); } catch (final sqliteConstraintException expected) { // expected conflict,should be original final Compound refresh = dao.refresh(conflict); assertNotNull(refresh); assertthat(refresh.id1,is(orig.id1)); assertthat(refresh.id2,is(orig.id2)); assertthat(refresh.data1,allOf(is(orig.data1),is(not(conflict.data1)))); assertthat(refresh.data2,allOf(is(orig.data2),is(not(conflict.data2)))); } }
public boolean insertarContacto(String nombre,String direccion,String telefono,int miembrofacebook,int miembrotwitter,int miembrogoogle,int miembrolinkedin,int sexo,String tipocontacto,int imagen){ sqliteDatabase db = getWritableDatabase(); if (db != null) { ContentValues valores = new ContentValues(); valores.put("nombre",nombre); valores.put("direccion",direccion); valores.put("telefono",telefono); valores.put("email",email); valores.put("miembrofacebook",miembrofacebook); valores.put("miembrotwitter",miembrotwitter); valores.put("miembrogoogle",miembrogoogle); valores.put("miembrolinkedin",miembrolinkedin); valores.put("sexo",sexo); valores.put("tipocontacto",tipocontacto); valores.put("imagen",imagen); //db.insert("contactos",valores); try { db.insertOrThrow(TABLA,valores); //TABLA por "contactos" return true; } catch (sqliteConstraintException e) { Log.d(TAG,"Fallo en la insercion: seguramente la clave ya existe."); } } db.close(); return false; }
public boolean insertarContacto(sqliteDatabase db,String nombre,int imagen){ if (db != null) { ContentValues valores = new ContentValues(); valores.put("nombre",nombre); valores.put("direccion",direccion); valores.put("telefono",telefono); valores.put("email",email); valores.put("miembrofacebook",miembrofacebook); valores.put("miembrotwitter",miembrotwitter); valores.put("miembrogoogle",miembrogoogle); valores.put("miembrolinkedin",miembrolinkedin); valores.put("sexo",sexo); valores.put("tipocontacto",tipocontacto); valores.put("imagen",imagen); //db.insert("contactos",valores); try { db.insertOrThrow(TABLA,valores); //TABLA por "contactos" return true; } catch (sqliteConstraintException e) { Log.d(TAG,"Fallo en la insercion: seguramente la clave ya existe."); } } return false; }
Extjs ajax读取 intraweb数据
自己搞定,备忘。
前台代码:
Ext.onReady(function(){
new Ext.FormPanel({
id:'typeForm',
renderTo: Ext.getBody(),宋体; font-size:14px; line-height:20px"> frame: true,宋体; font-size:14px; line-height:20px"> height: 300,宋体; font-size:14px; line-height:20px"> width:452,宋体; font-size:14px; line-height:20px"> buttonAlign:"center",宋体; font-size:14px; line-height:20px"> labelWidth: 50,宋体; font-size:14px; line-height:20px"> title: '函数',宋体; font-size:14px; line-height:20px"> items: [
{
xtype:'textareafield',宋体; font-size:14px; line-height:20px"> id:'myText',宋体; font-size:14px; line-height:20px"> height: 200,宋体; font-size:14px; line-height:20px"> width: 450,宋体; font-size:14px; line-height:20px"> wordWrap : true
},宋体; font-size:14px; line-height:20px"> new Ext.Button({
text:'...发送Ajax请求',宋体; font-size:14px; line-height:20px"> listeners:{
"click":function(){
Ext.Ajax.request({
url: '/$/callback?callback=IWCallBack1',//重点
method: 'POST',宋体; font-size:14px; line-height:20px"> success: function (response,options){
Ext.MessageBox.alert('成功','从服务端获取结果: ' + response.responseText);
Ext.getCmp("myText").setValue(response.responseText);
},宋体; font-size:14px; line-height:20px"> failure: function (response,宋体; font-size:14px; line-height:20px"> Ext.MessageBox.alert('失败','请求超时或网络故障,错误编号:' + response.status);
}
});
}
},宋体; font-size:14px; line-height:20px"> })
],//最大的ITEMS
});
});
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
后台intraweb代码:
procedure TIWForm1.IWAppFormCreate(Sender: TObject);
begin
LayoutMgr := IWTemplateProcessorHTML1;
WebApplication.RegisterCallBack('IWCallBack1',DoCallBack1); //重点
end;
procedure TIWForm1.DoCallBack1(EventParams: TStringList);
WebApplication.CallBackResponse.AddTagToUpdate('我是返回的数据,哈哈哈,搞定了哦!!'); //重点
end;
这个测试的意义是,可以用Extjs的强大功能做前台界面,intraweb只做后台,用ajax请求读取数据,摆脱对iw控件的依赖,可以把前后台分开(IW控件都是把前后台以及ajax封装在一起的)。
可以看到intraweb ajax Response返回的是XML。
IntraWeb
总结
以上是小编为你收集整理的IntraWeb全部内容。
如果觉得小编网站内容还不错,欢迎将小编网站推荐给好友。
关于使用 IntraWeb (43) - 测试读取 SqLite (二)的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于android.database.sqlite.SQLiteConstraintException、android.database.sqlite.SQLiteConstraintException的实例源码、Extjs ajax读取 intraweb数据、IntraWeb等相关知识的信息别忘了在本站进行查找喔。
本文标签: