2016-06-13 80 views
-1

我的代码下面的部分是工作完全正常,直到我重新启动我的电脑,现在它给我ArgumentException的错误是未处理的,出现此错误:的ArgumentException未处理

An unhandled exception of type 'System.ArgumentException' occurred in System.Data.dll

Additional information: Invalid value for key 'integrated security'

{ 
    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") 
+3

true not ture .. – Ian

回答

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以避免硬编码连接字符串。这将允许您访问连接字符串使用设置名称

+0

它说,它不能将查询从'字符串'转换为'System.Data.SqlClient.SqlCommand' – Carlos

+0

糟糕,忘了添加连接参数 –

+0

好的但是这样做它将允许用户输入他们想要的任何工具或零件号码,并且当输入的数据对任何一个不正确时我希望它出错。 – Carlos