我这样做:
var command = new SqlCommand(query, myConnection);
foreach (DataRow row in dt.Rows)
{
query = @"update FileLog set
FaxStatus=" + "'" + row.ItemArray[0].ToString() + "'," +
"FaxedPageCount=" + "'" + row.ItemArray[1].ToString() + "'," +
"dtFaxed=" + "'" + row.ItemArray[2].ToString() + "'," +
"RetryCount=" + "'" + row.ItemArray[4].ToString() + "' " +
"where JobID=" + "'" + row.ItemArray[3].ToString() + "'";
command = new SqlCommand(query, myConnection);
command.ExecuteNonQuery();
}
JobID
是uniqueidentifier
我收到了这个错误:
Conversion failed when converting from a character string to uniqueidentifier.
我做错了什么?
JobID字段如下所示:
DB9424E5-1E73-4108-A855-B252E516A2A2
2EB17B8B-C0A1-46FE-82AF-37AEF2A8A6EC
C24F0460-7667-4A3A-8D8F-64B9728C2359
8DCDB020-8C7B-493E-9D21-719CBAFC16B6
答案 0 :(得分:1)
这将更安全(从SQL注入安全),更易于阅读和理解,并且更快,因为准备好的语句可以缓存其执行计划。如果你有不同的sql,它就不能使用缓存的执行计划。
SqlCommand cmd =
new SqlCommand(
@"update FileLog set FaxStatus=@fs, FaxedPageCount=@ct, @dtFaxed=@dt, ......., where JobID=@id")
{CommandType = CommandType.Text};
cmd.Prepare();
cmd.Connection = connection;
cmd.Parameters["@id"].Value = row.ItemArray[0];
...
答案 1 :(得分:0)
我找到了解决方案。结果你需要这样做:
var command = new SqlCommand(query, myConnection);
foreach (DataRow row in dt.Rows)
{
query = @"update FileLog set
FaxStatus=" + "'" + row.ItemArray[0].ToString() + "'," +
"FaxedPageCount=" + "'" + row.ItemArray[1].ToString() + "'," +
"dtFaxed=" + "'" + row.ItemArray[2].ToString() + "'," +
"BiscomCode=" + "'" + row.ItemArray[5].ToString() + "', " +
"RetryCount=" + "'" + row.ItemArray[4].ToString() + "' " +
"where CONVERT(VARCHAR(255), JobID) =" + "'" + row.ItemArray[3].ToString() + "'";
command = new SqlCommand(query, myConnection);
command.ExecuteNonQuery();
}
你必须先将它转换为varchar
答案 2 :(得分:-1)
您的工作ID很可能不是有效的Guid。
这是检查guid的方法:
public static bool IsGuid(string input)
{
Regex isGuid = new Regex(@"^(\{){0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}(\}){0,1}$", RegexOptions.Compiled);
try
{
return isGuid.IsMatch(input);
}
catch
{
return false;
}
}
因此,在发出查询命令之前,请检查jobid。如果它不匹配,请将其转义并将其记录下来以便稍后重新访问。