无法在上次查询时将数据添加到我的数据库中

时间:2017-09-03 19:29:44

标签: c# sql sql-server

为什么我无法在最后一个查询(EventEndDate

上添加值
string insertQuery = "INSERT INTO eventreservation(EventID,CustomerName,CustomerIC," +
                      "CustomerPhone,StartDate,EndDate) VALUES('" + txtEventID.Text + "'," +
                      "'" + txtCustomerName.Text + "','" + txtCustomerIC.Text + "','" + 
                      txtCustomerPhone.Text + "','" + EventStartDate.Text + "'," + 
                      EventEndDate.Text + ")";

1 个答案:

答案 0 :(得分:2)

您在上一个条目中错过了单引号'

," + EventEndDate.Text + "

应该是:

,'" + EventEndDate.Text + "'

然而,这种字符串连接对SQL injection开放。请尝试使用parameterized queries。像这样:

string insertQuery = "INSERT INTO eventreservation(EventID,CustomerName,CustomerIC," +
                             "CustomerPhone,StartDate,EndDate)VALUES(@EventID,@CustomerName," +
                             "CustomerIC,@CustomerPhone,@StartDate,@EndDate)";
insertCommand.Parameters.AddWithValue(@EventID,txtEventID.Text);
//Other parameters

虽然直接指定类型并使用Value属性比AddWithValue更好:

insertCommand.Parameters.Add("@EventID", SqlDbType.VarChar).Value = txtEventID.Text;