我是C#的新手。未將對象引用設置爲對象的實例。請幫助解決錯誤
請告訴我這段代碼有什麼問題。我使用兩個輸入字段EndValueTextBox和StartValueTextBox將數據插入到數據庫中。
我收到以下錯誤。 「對象引用不設置到對象的實例」
private void buttonSave_Click(object sender, EventArgs e)
{
connection = new System.Data.SqlClient.SqlConnection();
da = new SqlDataAdapter();
try
{
connection.ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename='G:\\C#.Net\\Forms Practice\\WindowsFormsPractice1\\WindowsFormsPractice1\\WindowsFormsPractice1.mdf';Integrated Security=True;Connect Timeout=30;User Instance=True";
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message,"Connection String");
}
try
{
connection.Open();
string sql = "insert into TBLWORKERS (first_name , last_name)" + " values('" + StartValueTextBox.Text + "', '" + EndValueTextBox.Text + ")";
//SqlDataAdapter da = new SqlDataAdapter(query, connString);
da.InsertCommand.CommandText = sql;
da.InsertCommand.ExecuteNonQuery();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message, "Connection open");
}
}
關於您創建SQL的方式的警告。您有Sql注入的安全風險。這意味着如果有人會在其中一個texbox中輸入一些sql,而不是正常的開始/結束值,那麼sql將針對數據庫執行(例如,「drop table」命令!) –
@Wouter:OP沒有明白你的意思。如何提供一個鏈接到SQL注入文章,描述如何參數化? –
@RobertHarvey你是對的:)這個鏈接:http://www.csharp-station.com/Tutorials/AdoDotNet/Lesson06.aspx有一個很好的介紹如何構建一個SQL查詢 –