2011-05-01 149 views
1

在用Qt4製作的註冊軟件中,我打開Access .mdb數據庫,使用用戶提供的字段進行更新。訪問數據庫 - 自動插入更新 - Qt4

它目前是clients有桌子六個字段:

CustomerNumber, FullName, CNICNumber, ResidentialAddress, ResidentialPhoneNumber, MobileNumber 

其中CustomerNumber是主鍵和一個數字,而所有其他的文本。有幾條記錄存在。但與同CustomerNumber另一個記錄試圖插入,有一個錯誤:

QODBCResult::exec: Unable to execute statement: "[Microsoft][ODBC Microsoft Access Driver] The changes you requested to the table were not successful because they would create duplicate values in the index, primary key, or relationship. Change the data in the field or fields that contain duplicate data, remove the index, or redefine the index to permit duplicate entries and try again."

"[Microsoft][ODBC Microsoft Access Driver] The changes you requested to the table were not successful because they would create duplicate values in the index, primary key, or relationship. Change the data in the field or fields that contain duplicate data, remove the index, or redefine the index to permit duplicate entries and try again." "QODBC3: Unable to execute statement"

然後我找到了UPDATE查詢,但下面的代碼給出了另一個錯誤:

query.exec("UPDATE clients" 
"SET FullName='"+cname+"', CNICNumber='"+cnic+"', ResidentialAddress='"+caddress+"', ResidentialPhoneNumber='"+cphone+"', MobileNumber='"+cmobile+"'" 
"WHERE CustomerNumber="+cnumber+";"); 

變量cname, cninc, caddresss, cphone, cmobile, cnumber是具有值的字符串。但是,與上面的代碼錯誤是:

QODBCResult::exec: Unable to execute statement: "[Microsoft][ODBC Driver Manager] Function sequence error" "[Microsoft][ODBC Driver Manager] Function sequence error" "QODBC3: Unable to execute statement"

如何解決這一點,即如何插入新記錄時的主鍵不存在,但有相同的主鍵更新現有的記錄?

回答

4

您缺少空格。您執行的實際命令相當於

query.exec("UPDATE clientsSET Fullname... 

沒有這樣的表作爲clientsSET。

這裏是你打算

query.exec("UPDATE clients" 
    " SET FullName='"+cname+"', CNICNumber='"+cnic+"', ResidentialAddress='"+caddress+"', ResidentialPhoneNumber='"+cphone+"', MobileNumber='"+cmobile+"'" 
    " WHERE CustomerNumber="+cnumber+";"); 

如果這些用戶輸入值你容易受到SQL注入。您需要小心擦除所有字符串值(例如,用''替換所有')。

+0

實際上,用戶輸入值導致問題。我使用了'QSqlQuery :: bindValue',它工作 – yolo 2011-05-02 11:54:44

0
query.exec("UPDATE clients" 
...CNICNumber='"+cnic+"', ... 

我的猜測是CNICNumber不應該有單引號圍繞它。

...CNICNumber="+cnic+", ... 

但它不可能告訴肯定不知道你的表結構。

0

你可以嘗試用:

+ " SET FullName='"+cname+ ... 
+ " WHERE CustomerNumber="+cnumber+";"); 
第二排和第三排的

1

What is the solution to this, i.e. how to insert a new record when the primary key is not present but update existing record with same primary key?

這是非正式稱爲UPSERT。請參閱與Access相關的this answer