如何在参数化查询中传递 guid?
我当前最好的代码是:
string delNonQuery = "DELETE FROM " + Settings.DataSource + " WHERE @keycolumn=@keyuid";
SqlCommand cmd = new SqlCommand(delNonQuery,readerConn);
SqlParameter kc = new SqlParameter("keycolumn", SqlDbType.VarChar);
SqlParameter key = new SqlParameter("keyuid", SqlDbType.VarChar);
cmd.Parameters.Add(kc).Value = Settings.KeyColumn;
cmd.Parameters.Add(key).Value = Page.Request["key"].ToString().Trim();
readerConn.Open();
cmd.ExecuteScalar();
readerConn.Close();
它执行但影响了惊人的零行。如果我将 keyuid 上的 SqlDbType 更改为 UniqueIdentifier,最终会出现“无法将字符串转换为 uniqueidentifier”的十几个变体。我必须使用参数化查询来保持数据清洁度,我只是真的不知道如何......
My current best code is:
string delNonQuery = "DELETE FROM " + Settings.DataSource + " WHERE @keycolumn=@keyuid";
SqlCommand cmd = new SqlCommand(delNonQuery,readerConn);
SqlParameter kc = new SqlParameter("keycolumn", SqlDbType.VarChar);
SqlParameter key = new SqlParameter("keyuid", SqlDbType.VarChar);
cmd.Parameters.Add(kc).Value = Settings.KeyColumn;
cmd.Parameters.Add(key).Value = Page.Request["key"].ToString().Trim();
readerConn.Open();
cmd.ExecuteScalar();
readerConn.Close();
This executes but affects a whopping zero rows. If I change the SqlDbType on keyuid to UniqueIdentifier it just ends up with me getting a dozen variations on "failed to convert character string into uniqueidentifier". I have to use a parameterized query for data cleanliness, I'm just really stuck as to how...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您无法为列名指定参数 - 您需要以与表名相同的方式连接它。
这:
应该更改为:
虽然我可能会将其写为:
为了完整性起见,我会提到这对 SQL注入。您需要确保您的
设置
值是干净的。You can't specify a parameter for a column name - you need to concatenate it the same way you do for the table name.
This:
Should change to:
Though I would probably write it as:
For completeness sake, I will mention that this is open to SQL injection. You need to make sure your
Settings
values are clean.我不认为你可以参数化列名(“keycolumn”)
尝试这个:
关于连接字符串来构建 SQL 的常见警告;这可能是一个安全风险。
最好的方法可能是将 SQL 封装在存储过程中,将列名和值作为参数传递,然后使用动态 SQL 执行。
I don't think you can parameterise the column name ("keycolumn")
Try this:
Usual warnings apply regarding concatanating strings to build SQL; this is likely a security risk.
The best method might be to encapsulate your SQL in a stored procedure, pass the column name and value as parameters and then execute using dynamic SQL.
您需要将字符串转换为 GUID:
相关行:
这仅解决 GUID/UniqueIdentifer 问题
You need to convert the string to GUID:
Relevant Lines:
Which only solves the GUID/UniqueIdentifer issue