2014-05-11 202 views
0

我想基本的數據庫插入這個代碼是啥子我在Visual Studio正在運行2010: -拋出異常:連接屬性尚未初始化

protected void Button1_Click(object sender, EventArgs e) 
{ 
    SqlConnection conn = new SqlConnection(); 
    conn.ConnectionString="Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\Administrator\\Documents\\Visual Studio 2010\\WebSites\\WebSite3\\App_Data\\name.mdf;Integrated Security=True;User Instance=True"; 

    SqlCommand cmd = new SqlCommand("insert into names values('" + TextBox1.Text + "')"); 
    conn.Open(); 
    cmd.ExecuteNonQuery(); 
    conn.Close(); 

} 

我在哪裏錯了?

+0

您沒有添加連接給SqlCommand - '的SqlCommand CMD =新的SqlCommand(「插入名稱VALUES('」 + TextBox1.Text +「' )「,conn);'或'cmd.Connection = conn;'。另外,學習參數化查詢以防止SQL注入攻擊。 – Tim

回答

0

您沒有指定connection to the command object。請嘗試:

protected void Button1_Click(object sender, EventArgs e) 
{ 
    SqlConnection conn = new SqlConnection(); 
    conn.ConnectionString="Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\Administrator\\Documents\\Visual Studio 2010\\WebSites\\WebSite3\\App_Data\\name.mdf;Integrated Security=True;User Instance=True"; 

    SqlCommand cmd = new SqlCommand("insert into names values('" + TextBox1.Text + "')"); 
    cmd.Connection = conn; // <- this is the missing line 
    conn.Open(); 
    cmd.ExecuteNonQuery(); 
    conn.Close(); 

} 
1

您創建了一個連接並將其打開,但未將其與SqlCommand關聯。您可以通過幾種方法執行此操作,無論是在SqlCommand的構造函數中還是通過SqlCommandConnection屬性。

此外,您應該使用參數化查詢來防止SQL注入攻擊。我還建議將SqlConnection放在使用區塊中,以確保它關閉並妥善處理。把所有的一起爲您提供了這樣的事情:

protected void Button1_Click(object sender, EventArgs e) 
{ 

    using (SqlConnection conn = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\Administrator\\Documents\\Visual Studio 2010\\WebSites\\WebSite3\\App_Data\\name.mdf;Integrated Security=True;User Instance=True")) 
    { 
     conn.Open(); 
     SqlCommand cmd = new SqlCommand("insert into names values(@name)", conn); 
     // Alternatively, you could do cmd.Connection = conn if you didn't pass 
     // the connection object into the SqlCommand constructor 
     cmd.Parameters.AddWithValue("@name", TextBox1.Text); 

     cmd.ExecuteNonQuery(); 
    } 
} 
相關問題