我想了解如何獲取控制值並將它們插入到數據庫表中。例如,我有一個名爲NameBox
的文本框。我想從該文本框中獲取文本並將其添加到數據庫表中。以2個文本框值插入到SQL Server數據庫
我不是試圖做到最好的方式,但最簡單的,所以我可以通過頭圍繞概念包裝。到目前爲止,我有:
<asp:TextBox ID="NameBox" runat="server"></asp:TextBox>
<asp:TextBox ID="EmailBox" runat="server"></asp:TextBox>
這裏是代碼隱藏。
我越來越protected void Button1_Click(object sender, EventArgs e)
{
string name1 = NameBox.Text;
string email1 = EmailBox.Text;
System.Data.SqlClient.SqlConnection sqlConnection1 =
new System.Data.SqlClient.SqlConnection(@"Data Source=E:\*********.com1.5\**********.com\App_Data\Home.sdf;");
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "INSERT INTO CustomerList (Name, Email) VALUES (" + name1 + "," + email1 + ")";
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
cmd.ExecuteNonQuery();
sqlConnection1.Close();
}
錯誤消息
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
我GOOGLE了錯誤信息,很多是我一直在讀的喊着我的連接可能是錯誤的。我試着通過使用一些拖放控件來測試它,並且我有一個使用相同連接字符串的中繼器。
現在我甚至不知道這是否正確。我相信你們都可以在某個方面或某個方面有所聯繫,我希望看到它在一個非常簡單的層面上工作,所以我可以開始玩它,看看它是如何工作的。
兩個詞:參數化查詢 – LittleBobbyTables
作爲閱讀你發現表明,它有連接問題,所以它要麼你的連接字符串,或者,你可以找一些環境因素訪問它。而對於皮特的愛...參數化! –
但是從那裏SQL查詢不正確;字符串沒有被撇號包圍,並且即使它們是注入攻擊也很容易受到攻擊。請參閱:http://www.codinghorror.com/blog/2005/04/give-me-parameterized-sql-or-give-me-death.html – LittleBobbyTables