我在将SQL语句添加日期字段时遇到问题 - 没有语法错误,但是它会将日期保存为1905-06-17任何提示吗?
var是
ExpireDate : String;
值
ExpireDate := DateToStr(IncYear(Today,1));
声明
datamodule1.qryDB1.SQL.Text := 'INSERT INTO table SET Member_ExpireDate = '+ ExpireDate +' WHERE Member_ID = .................';
答案 0 :(得分:1)
您使用的DateToStr()
版本依赖于用户当前的操作系统区域设置。数据库具有特定的格式,他们希望表达日期/时间字符串,并且操作系统的语言环境设置可能与这些格式不匹配。您可以使用DateToStr()
的重载版本作为输入TFormatSettings
,以便您可以指定输出字符串的确切格式(通过TFormatSettings.ShortDateFormat
成员):
var
fmt: TFormatSettings;
ExpireDate: string;
fmt := TFormatSettings.Create;
fmt.ShortDateFormat := 'yyyy-mm-dd';
ExpireDate := DateToStr(IncYear(Today,1), fmt);
此外,日期/时间字符串需要在SQL语句中用引号括起来。您可以将QuotedStr()
功能用于此目的。
但更重要的是,无论如何,您的INSERT
陈述都是错误的。
如果您尝试添加新记录,则需要更像这样:
datamodule1.qryDB1.SQL.Text := 'INSERT INTO table (Member_ID, Member_ExpireDate) VALUES (' + SomeIDValue + ', ' + QuotedStr(ExpireDate) + ')';
否则,如果您尝试修改现有记录,则需要使用UPDATE
语句:
datamodule1.qryDB1.SQL.Text := 'UPDATE table SET Member_ExpireDate = ' + QuotedStr(ExpireDate) + ' WHERE Member_ID = ' + SomeIDValue;
无论哪种方式,最好使用参数化查询。让DB本身为您处理所有必要的格式:
datamodule1.qryDB1.SQL.Text := 'INSERT INTO table (Member_ID, Member_ExpireDate) VALUES (:MemberID, :ExpireDate)';
datamodule1.qryDB1.ParamByName('MemberID').AsInteger := SomeIDValue; // or whatever data type your field uses
datamodule1.qryDB1.ParamByName('ExpireDate').AsDate := IncYear(Today,1);
datamodule1.qryDB1.ExecSQL;
datamodule1.qryDB1.SQL.Text := 'UPDATE table SET Member_ExpireDate = :ExpireDate WHERE Member_ID = :MemberID';
datamodule1.qryDB1.ParamByName('ExpireDate').AsDate := IncYear(Today,1);
datamodule1.qryDB1.ParamByName('MemberID').AsInteger := SomeIDValue; // or whatever data type your field uses
datamodule1.qryDB1.ExecSQL;
答案 1 :(得分:1)
不要将日期转换为字符串。将数据作为日期插入并使用参数来最小化错误。使用参数组件将datatime格式化为正确的格式。
var
ExpireDate : TDate;
begin
ExpireDate := IncYear(Today,1);
datamodule1.qryDB1.SQL.Text :=
'INSERT INTO table SET Member_ExpireDate = :expireDate WHERE Member_ID = ..';
datamodule1.qryDB1.Params.ParamByName('expireDate').Value := ExpireDate;
根据您使用的组件,ParamByName
可能会有所不同,但所有TQuery
后代组件都有此方法。
问候。
答案 2 :(得分:0)
感谢您解决了响应问题...应该使用#'+ ExpireDate +'#所有工作都很棒谢谢。