ArgumentException未处理

时间:2016-06-13 15:27:33

标签: c#

我的代码的以下部分工作正常,直到我重新启动计算机,现在它给了我ArgumentException的错误未处理此错误:

  

未处理的类型' System.ArgumentException'发生在   System.Data.dll中

     

其他信息:密钥'集成安全性'

的值无效
{
    SqlConnection con = new SqlConnection(@"Data Source=M2192822\SHIFTREPORTS;Initial Catalog=ShiftReports;Integrated Security=ture");
    SqlDataAdapter sda = new SqlDataAdapter("Select Count(*) From [All of Production] where Tool ='" + MoldText.Text + "' and [Internal Part Number] ='" + IPNText.Text + "'", con);
    DataTable dta = new DataTable();
    sda.Fill(dta);
    MessageBox.Show("Part or Mold Number is Incorrect");
}

if (dta.Rows[0][0].ToString() != "1")

1 个答案:

答案 0 :(得分:3)

如错误消息所示,ture不是Integrated Security的有效值。您应该使用Integrated Security=true

代码还有其他更严重的问题。首先,连接没有关闭。其次,您正在使用字符串连接创建SQL语句,这是将您自己暴露给SQL注入攻击的可靠方法。想象一下如果用户输入1';drop table Products;--

会发生什么

正确关闭连接并使用参数化查询实际上比字符串连接更容易:

var connString = @"Data Source=M2192822\SHIFTREPORTS;Initial Catalog=ShiftReports;Integrated Security=true";
var query="Select Count(*) From [All of Production] where Tool = @tool and [Internal Part Number] = @part";
DataTable dta = new DataTable();

using(var con = new new SqlConnection(connString))
using(var sda=new SqlDataAdapter(query, con)
{
     var cmdParameters=sda.SelectCommand.Parameters;
     parameters.AddWithValue("@tool",MoldText.Text);
     parameters.AddWithValue("@part",IPNText.Text);
     sda.Fill(dta);
}

您可以将连接字符串作为Connection String类型的参数存储在应用程序的设置中,以避免对连接字符串进行硬编码。这将允许您使用设置名称

访问连接字符串
相关问题