Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/258.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#插入查询执行_C#_.net - Fatal编程技术网

C#插入查询执行

C#插入查询执行,c#,.net,C#,.net,我已经在运行时在数据库中插入了一行,如果执行成功,它应该显示肯定的消息如果没有执行,它应该显示否定的消息。我只做了肯定的场景,我也希望得到否定的消息。请帮帮我,伙计们 SqlCommand sc = new SqlCommand("insert into Master Values('" + textBox1.Text + "'," + textBox2.Text + "," + textBox3.Text + ",'" + textBox4.Text + "','" + textBox5.Te

我已经在运行时在数据库中插入了一行,如果执行成功,它应该显示肯定的消息如果没有执行,它应该显示否定的消息。我只做了肯定的场景,我也希望得到否定的消息。请帮帮我,伙计们

SqlCommand sc = new SqlCommand("insert into Master Values('" + textBox1.Text + "'," + textBox2.Text + "," + textBox3.Text + ",'" + textBox4.Text + "','" + textBox5.Text + "','" + textBox6.Text + "','" + textBox7.Text + "','" + textBox8.Text + "','" + textBox9.Text + "');");
            sc.Connection = con;
            int o;
o = sc.ExecuteNonQuery();
            MessageBox.Show("saved");

为了确定查询的“成功”,您需要检查几件事情。具体而言:

  • 例外情况
  • 受影响的行
  • 第一个由异常处理处理。例如:

    try
    {
        ...
        o = sc.ExecuteNonQuery();
        MessageBox.Show("saved");
    }
    catch (SqlException e)
    {
        // there was an error from the database, handle it here
    }
    
    第二个可以通过存储在
    o
    中的返回值进行检查。(顺便说一下,这是一个非常不直观的变量名。)类似于:

    if (o < 1)
    {
        // no rows were updated, handle that condition here
    }
    

    旁注:请注意,您的代码是完全开放的。您需要使用来帮助防范这种情况。

    考虑将SQL重新表述为参数化查询,这样您就不会设置SQL注入。您建议如何检测查询失败?o=sc.ExecuteNonQuery();如果此代码成功执行,将在o中存储一个值。然后我们可以发出一条信息,说明数据已保存。如果查询是错误的,上述语句的执行将显示错误,并且o中不会存储任何值,那么我们如何显示执行不成功。@user3840562:您向用户显示什么或如何显示它取决于您自己。但是,您要查找的条件是异常或结果中的意外值。我们可以检查sc.ExecuteNonQuery()的循环吗?@user3840562:恐怕这个评论没有意义…谢谢您…先生…异常方法…工作正常
    if (o > 1)
    {
        // *multiple* rows were updated, is that what you wanted?
    }