gpt4 book ai didi

mysql - 字段列表中的未知列

转载 作者:可可西里 更新时间:2023-11-01 08:39:42 24 4
gpt4 key购买 nike

我试图用 Pascal 向 MySQL 插入一些信息,但是当我运行该程序时出现错误

unknown column 'mohsen' in field list

这是我的代码

procedure TForm1.Button1Click(Sender: TObject);
var
aSQLText: string;
aSQLCommand: string;
namee:string;
family:string;
begin
namee:='mohsen';
family:='dolatshah';
aSQLText:= 'INSERT INTO b_tbl(Name,Family) VALUES (%s,%s)';
aSQLCommand := Format(aSQLText, [namee, family]);
SQLConnector1.ExecuteDirect(aSQLCommand);
SQLTransaction1.Commit;
end;

我该如何解决这个问题?

最佳答案

因为你的

VALUES (%s,%s)

没有用引号将 namee 和 family 变量内容括起来。因此,你的后端Sql引擎认为你的mohsen是一个列名,而不是一个值。

而是使用,例如

VALUES (''%s'',''%s'')

如在

  Namee := 'mohsen';
Family := 'dolatshah';
aSQLText:= 'INSERT INTO b_tbl(Name,Family) VALUES (''%s'',''%s'')';
aSQLCommand := Format(aSQLText,[namee,family]);

在我的回答的原始版本中,我解释了如何通过在您尝试构建的 Sql 中“加倍”单引号来解决您的问题,因为在我看来您很难(字面上)看到什么是你做的错了。

避免问题的另一种(更好)方法(也是我在现实生活中经常使用的方法)是使用 QuotedStr() 函数。相同的代码将变成

aSQLText := 'INSERT INTO b_tbl (Name, Family) VALUES (%s, %s)'; 
aSQLCommand := Format(aSQLText, [QuotedStr(namee), QuotedStr(family)]);

根据在线帮助:

Use QuotedStr to convert the string S to a quoted string. A single quote character (') >is inserted at the beginning and end of S, and each single quote character in the string is >repeated.

“重复”的意思就是我所说的“加倍”。为什么这很重要,我使用 QuotedStr 的主要原因是为了避免 Sql 数据库引擎在您要发送的值包含单引号字符时抛出错误,如 O'Reilly

尝试使用 MySql Workbench 将包含该名称的行添加到您的表中,您就会明白我的意思。

因此,使用 QuotedStr 不仅可以使在 Delphi 代码中将 SQL 语句构造为字符串更不容易出错,而且还可以避免后端出现问题。

关于mysql - 字段列表中的未知列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38253421/

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