gpt4 book ai didi

python - adsdb 插入

转载 作者:行者123 更新时间:2023-11-29 20:50:35 25 4
gpt4 key购买 nike

我有一个可以使用 Advantage Data Architect 修改的 ADT。

但是我希望能够使用 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 上搜索了提供的错误代码,但几乎没有找到解决方案。

最佳答案

在 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注入(inject)。

正确的方法是使用参数:

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

顺便说一句:“Persons”是一个糟糕的表名(person 的复数是 people,你应该使用“person”或“people”作为表名)。

关于python - adsdb 插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38094384/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com