使用检查值插入查询? [英] insert query with check values?

查看:49
本文介绍了使用检查值插入查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在sql中有一个数据表MapImageData,它包含



Id(Int)

source(varchar(max))

目的地(varchar(max))

User_comment(varchar(max))



我也有gui ..其中持有源,目的地和用户评论文本框



所以问题是

i希望用sql数据库源和目的地检查用户输入源和目的地.. 。

如果正确

i也想添加用户评论



i have a datatable MapImageData in sql which holds

Id(Int)
source(varchar(max))
destination(varchar(max))
User_comment(varchar(max))

also i have gui.. which holds source, destination and usercomment textboxes

so the problem is
i want to check userinput source and destination with sql database source and destination...
and if its correct
i want to add user comment also

String QueryStr = "INSERT INTO MapImageData(User_Comment) VALUES (@User_Comments)" WHERE Source='" + Source_Box.Text + "' AND Destination='" + Distance_Box.Text + "'";
SqlCommand scmd1 = new SqlCommand(QueryStr, conn2);

scmd1.Parameters.AddWithValue("@User_Comments", UserComment.Text);





但有人说我不能使用带插入条件的地方..



所以如何解决他的问题.........



but someone said i can't use where condition with insert..

so how can i solve his problem.........

推荐答案

你不能使用WHERE条件INSERT,因为WHERE用于过滤返回的结果或限制受影响的行的范围 - INSERT 始终 创建一个新行,因此它不能过滤或限制。

或许,你想要做的是检查一行是否存在,如果不存在则插入它,或者如果它存在则使用UPDATE进行修改。



创建一个存储过程可能值得这样做:这就是你的C#代码中的一个简单的单个命令。



但请不要这样做SQL!不要连接字符串以构建SQL命令。它让您对意外或故意的SQL注入攻击持开放态度,这可能会破坏您的整个数据库。请改用参数化查询。
You cannot use a WHERE condition with an INSERT at all, because WHERE works to filter the results returned or limit the range of rows that are affected - an INSERT always creates a new row, so it can't be filtered or restricted.
Probably, what you want to do it check if a row exists, and INSERT it if it doesn't, or use UPDATE to modify it if it does exist.

It might be worth creating a stored procedure to do this: that way it's just a simple single command in your C# code.

But please, don't ever do SQL like that! Do not concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Use Parametrized queries instead.


这篇关于使用检查值插入查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆