请更正我的插入查询 [英] Please correct my insert query

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

问题描述

  string  str =   insert into + label4.Text +  '(dataid,data)values('+textBox1.Text+ ',' + label2.Text +  '); 
SqlCommand cmd = new SqlCommand(str,con);
cmd.ExecuteNonQuery();
MessageBox.Show( 插入值!);





我的尝试:



当我运行它时出现此错误

'='附近的语法不正确。

字符串')'后面的未闭合引号。

解决方案

不要连接字符串来构建SQL命令。它让您对意外或故意的SQL注入攻击持开放态度,这可能会破坏您的整个数据库。请改用参数化查询。

这可能会同时解决您的问题。

特别是如果您在开放括号之前删除备用报价:

  string  str =   INSERT INTO MyTable(dataid,data)VALUES(@DI,@ DT); 
SqlCommand cmd = new SqlCommand(str,con);
cmd.Parameters.AddWithValue( @ DI,textBox1.Text);
cmd.Parameters.AddWithValue( @ DT,label2.Text);


Google用于C#参数化sql查询以解决此问题。此解决方案的唯一问题是您无法参数化表名称。由于您使用标签来保存表名,我不知道为什么您首先使用标签来保存名称。



接下来,谷歌针对Sql Injection Attack找出你目前正在做的事情是如此糟糕。您可能无意中或故意使用您编写的代码破坏数据库。


使用调试器检查str变量的内容,它看起来像;



 插入 进入 mytable ' (dataid,data)值('  1  ' ,'一个'  





这是有效的SQL吗?不,你有一个不需要的引号(在表名后)这正是错误信息告诉你的那个



  string  str =  插入 + label4。文本+  (dataid,data)值(' + textBox1.Text +  ',' + label2.Text +  '); 


string str = "insert into "+label4.Text+"'(dataid,data) values('"+textBox1.Text+"','"+label2.Text+ "')";
SqlCommand cmd = new SqlCommand(str,con);
cmd.ExecuteNonQuery();
MessageBox.Show("values inserted!");



What I have tried:

when i'm running it this error comes
Incorrect syntax near '='.
Unclosed quotation mark after the character string ')'.

解决方案

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.
The chances are that that will cure your problem at the same time.
Especially if you get rid of the spare quote before your open bracket:

string str = "INSERT INTO MyTable (dataid,data) VALUES (@DI, @DT)";
SqlCommand cmd = new SqlCommand(str,con);
cmd.Parameters.AddWithValue("@DI", textBox1.Text);
cmd.Parameters.AddWithValue("@DT", label2.Text);


Google for "C# parameterized sql queries" for the solution to this problem. The only problem with this solution is that you can NOT parameterize the table name. Since you're using a label to hold the table name I don't know why you're ever using a label to hold the name in the first place.

Next, Google for "Sql Injection Attack" to find out why what you're currently doing is so bad. You risk destruction of your database, either inadvertently or intentionally with the code you've written.


Use the debugger to examine the contents of the str variable and it will look like;

insert into mytable'(dataid,data) values('1','One')



Is that valid SQL? No, you have an unneeded quotation mark (after the table name) which is exactly what the error message is telling you

string str = "insert into "+label4.Text+" (dataid,data) values('"+textBox1.Text+"','"+label2.Text+ "')";


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

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