sql server 2005删除问题 [英] sql server 2005 deleting problem

查看:60
本文介绍了sql server 2005删除问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我想用c#删除sql中的一条记录,这是我的代码,但是有问题:

Hi,
I want to delete a record in sql with c# , it''s my code but it has problem :

private void button1_Click(object sender, EventArgs e)
        {
            SqlConnection s = new SqlConnection(@"DataSource=.\SQLEXPRESS;AttachDbFilename=C:\Users\mm\Documents\Visual Studio 2008\Projects\LAS\LAS\mm.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
            string delstring = textBox1.Text;
            SqlCommand com = new SqlCommand("DELETE bookInfo WHERE bookName=" + delstring, s);
            s.Open();
            com.ExecuteNonQuery();
            s.Close();
        }


请告诉我如何解决它的问题.


please tell me how can I solve it''s problem.

推荐答案

如果出现错误,通常就是一个提示.
如果不是,那么您需要查看您的数据.

可能是您的数据才是问题所在.您的书名是否包含空格或标点符号?如果是这样,那么它将破坏SQL命令.为避免这种情况(以及意外或故意的SQL注入攻击),请改用参数化查询:
If it gives you an error, that is normally a clue.
If it doesn''t, then you need to look at your data.

The chances are it is your data that is the problem. Does your book name contain any spaces or punctuation? If so, then it will muck up the SQL command. To avoid that (and accidental or deliberate SQL Injection attacks) use parametrized queries instead:
private void button1_Click(object sender, EventArgs e)
        {
            SqlConnection s = new SqlConnection(@"DataSource=.\SQLEXPRESS;AttachDbFilename=C:\Users\mm\Documents\Visual Studio 2008\Projects\LAS\LAS\mm.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
            string delstring = textBox1.Text;
            SqlCommand com = new SqlCommand("DELETE bookInfo WHERE bookName=@BN", s);
            com.AddWithValue("@BN", delstring);
            s.Open();
            com.ExecuteNonQuery();
            s.Close();
        }


不要以为您错过了这里的东西:
("DELETE bookInfo WHERE bookName=" + delstring, s);

您指的是哪个表?
试试:
("DELETE FROM bookInfo WHERE bookName=" + delstring, s);
假设"bookInfo"是表名.


更新:
我还注意到,书名值在这里没有用引号引起来.它看起来像一个字符串,应该是数据库中的varchar,因此需要使用引号.

因此,请尝试:
("DELETE FROM bookInfo WHERE bookName=''" + delstring+"''", s);
Don''t you think you missed something here:
("DELETE bookInfo WHERE bookName=" + delstring, s);

Which table you are referring to?
Try:
("DELETE FROM bookInfo WHERE bookName=" + delstring, s);
Assuming, ''bookInfo'' is the table name.


UPDATE:
I also notice that bookname value is not surrounded by a quote here. It looks like a string, varchar in DB it should be and thus quotes would be needed.

Thus, try:
("DELETE FROM bookInfo WHERE bookName=''" + delstring+"''", s);


这篇关于sql server 2005删除问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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