且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

查询中的python mysql错误

更新时间:2023-01-29 21:42:36

首先,正如这里所说:检查有效的 SQL 列名

SQL 标识符和关键字必须以字母(a-z,但也可以是带有变音符和非拉丁字母的字母)或下划线 (_) 开头.标识符或关键字中的后续字符可以是字母、下划线、数字 (0-9) 或美元符号 ($).请注意,根据 SQL 标准的字母,标识符中不允许使用美元符号,因此使用它们可能会使应用程序的可移植性降低

SQL identifiers and key words must begin with a letter (a-z, but also letters with diacritical marks and non-Latin letters) or an underscore (_). Subsequent characters in an identifier or key word can be letters, underscores, digits (0-9), or dollar signs ($). Note that dollar signs are not allowed in identifiers according to the letter of the SQL standard, so their use might render applications less portable

它来自 PostGre doc,但因为 PostGre 非常接近理想"的 SQL 语法,它可能与 mysql 相同......所以列名中没有括号,没有空格......

It comes from PostGre doc, but because PostGre is very close to the "ideal" SQL syntax, it might be the same for mysql... So no parenthesis into column names, no spaces...

其次,列名不是字符串:

以下语法有效:

CREATE TABLE (test VARCHAR(100) NOT NULL, ...)

而以下无效,会抛出语法错误:

And the following one is invalid and will throw a syntax error:

CREATE TABLE ('test' VARCHAR(100) NOT NULL, ...)

当您使用%s"修饰符时,它会将数据解析为 STRING.所以它用引号括起来,这是无效的...

When you use the '%s' modifier, it parses data as STRING. so it surrounds it with quotes, which is invalid...

因此,为了创建您的表,我建议使用for 循环"来验证数据(使用 regexpr),并将其添加到字符串中:

So for create your table, I suggest a "for loop" which validate data (with regexpr), and symply add it to the string:

import re
# ...
query = "CREATE TABLE test (ID INT AUTO_INCREMENT,name VARCHAR(50)"
for c in columnames:
        if (re.search(r"^[A-Za-z][A-Za-z0-9_]*$", c) query += c + ", FLOAT" #this regex validate string if  it begins with alphabetic char (upper or lower case), and if the others characters are alphanumeric, or are underscores
        else raise SyntaxError("Invalid Column name!!") #If not, we raise a syntax error
query += ");"

然后你可以创建你的表:)

And then you can create your table :)