2016-06-29 48 views
0

我有一個ADT,可以使用Advantage Data Architect進行修改。adsdb INSERT INTO

但我希望能夠使用adsdb修改表。我已經創建了使用;

cnxn = adsdb.connect(DataSource='c:/Python27/', ServerType='1') 
cursor = cnxn.cursor() 
cursor.execute('CREATE TABLE Persons (PersonID INTEGER, LastName CHAR(100), FirstName CHAR(100))' 

我能夠插入數據到PersonsID字段使用;

cursor.execute('INSERT INTO Persons (PersonID) VALUES (01)') 

但試圖將數據插入char類型的列使用;

cursor.execute('INSERT INTO Persons (LastName) VALUES ("Smith")') 

我得到錯誤;

adsdb.OperationalError: Error 7200: AQE Error: State = S0000; NativeError = 2121; [iAnywhere Solutions][Advantage SQL Engine]Column not found: Smith -- Location of error in the SQL statement is: 40 

我試過在VALUE字段中使用單引號和沒有引號,但我仍然出現錯誤。我已經提供了Google提供的錯誤代碼,但是我找不到解決方案。

回答

0

在ADS SQL(實際上在ANSI-SQL)字符串(CHAR類型)值have to be enclosed in single quotes

INSERT INTO Persons (LastName) VALUES ('Smith') 

In Python a string literal既可以寫在單或雙引號:

print("Hello") 
print('Hello') 

由於正確的SQL語句不包含雙引號,因此使用雙引號字符串會更容易:

cursor.execute("INSERT INTO Persons (LastName) VALUES ('Smith')") 

如果你想使用一個單引號字符文字,你有逃脫的文字裏面的單引號:

cursor.execute('INSERT INTO Persons (LastName) VALUES (\'Smith\')') 

但使用字符串插值或字符串連接來獲得我不會那樣做,因爲值轉換爲SQL語句is very dangerous,並可導致SQL注入。

正確的方法是使用一個參數:

cursor.execute('INSERT INTO Persons (LastName) VALUES (?)', 'Smith') 

BTW:「人」是一個可怕的表名(的人多的是人,您應該使用「人」奧德「人」爲表名)。

+0

明智的答案謝謝你。謝謝你的提示,Persons表只是爲了測試:) – apmacniven