我正在尝试创建一个Web表单,其中来自多个文本框的数据将数据输入到我创建的n SQL数据库中。我的代码列在下面,问题是当它编译时,它就好像它没有。 messagedisplay.text不会更改,并且SQL数据库不会更新。有谁知道解决方案?
protected void createButton_Click(object sender, EventArgs e)
{
string state = stateTextBox.Text;
string country = countryTextBox.Text;
string lake = lakeTextBox.Text;
SqlConnection connection = new SqlConnection("Data Source=.MetricSample;Initial Catalog=ElementID;"+ "Integrated Security=true;");
connection.Open();
try
{
using (SqlCommand command = new SqlCommand(
"INSERT INTO ResearcherID VALUES(@ResearcherFname, @ResearcherLName)", connection))
{
command.Parameters.Add(new SqlParameter("ResearcherFName", country));
command.Parameters.Add(new SqlParameter("ResearcherLName", state));
command.ExecuteNonQuery();
}
messageDisplay.Text = "DB Connection Successfull";
}
catch
{
messageDisplay.Text = "DB Connection Failed";
}
}
答案 0 :(得分:1)
试试这个
using (SqlCommand sqlCmd = new SqlCommand("INSERT INTO ResearcherID (FieldNameForFirstName, FieldNameForLastName) VALUES (@ResearcherFname, @ResearcherLName)", sqlConn)) {
sqlCmd.Parameters.AddWithValue("@ResearcherFname", country);
sqlCmd.Parameters.AddWithValue("@ResearcherLName", state);
}
也可以在connection.Open();
try