windows窗体应用程序中的列名无效如何解决? [英] invalid column name in windows forms application how to solve it?

查看:246
本文介绍了windows窗体应用程序中的列名无效如何解决?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

按钮点击事件



in button click event

private void button3_Click(object sender, EventArgs e)
        {
            SqlStr = String.Format("insert into employee(empid,ename,salary,deptno) values ({0},{1},{2},{3})", textBox1.Text, textBox2.Text, textBox3.Text, textBox4.Text);
            ExecuteDML();
            button3.Enabled = false;
        }





命令执行方法我写了这样的代码





in command exection method i have written the code like this

private void ExecuteDML()
{
    DialogResult d = MessageBox.Show("Are you sure of executing the below SQl Statement?\n\n" + SqlStr, "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
    if(d==DialogResult.Yes)
    {
        cmd.CommandText = SqlStr;
        int Count = cmd.ExecuteNonQuery();
        if(Count>0)
        {
            MessageBox.Show("Statement executed Successfully");
        }
        else
        {
            MessageBox.Show("Statement failed execution");
        }
        LoadData();
    }
}





但我在执行代码时收到无效的列名错误。

有人帮我谢谢。



but i am getting the invalid column name error while executing the code.
someone help me thanks.

推荐答案

基本上是因为你从文本框中添加值而没有开始和结束'。



然而更大的问题是你不使用参数。



修正这个问题的正确方法是使用 SqlParameter [ ^ ]

所以代替

Basically the error comes because you add the values from the text boxes without having starting and ending '.

However the bigger problem is that you don't use parameters.

Correct way to fix this is to use SqlParameter[^]
So instead of
SqlStr = String.Format("insert into employee(empid,ename,salary,deptno) values ({0},{1},{2},{3})", textBox1.Text, textBox2.Text, textBox3.Text, textBox4.Text);
ExecuteDML();



你应该有类似


You should have something like

SqlStr = "insert into employee(empid,ename,salary,deptno) values (@empid,@ename,@salary,@deptno)");
ExecuteDML();



然后使用 AddWithValue [ ^ ]您将参数添加到要使用的命令的参数集合中。


and then using AddWithValue[^] you add the parameters to the parameter collection of the command to be used.


这篇关于windows窗体应用程序中的列名无效如何解决?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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