0

我正在尝试创建一个 Web 表单,其中来自多个文本框的数据会将数据输入到我创建的 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";
            }




    }
4

1 回答 1

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

于 2012-05-18T16:29:14.640 回答