-5

保存到 SQL Server 2005 时出现问题:

cmd = new SqlCommand("INSERT into survey_Request1(sur_no,sur_custname,sur_address,sur_emp,sur_date,sur_time,Sur_status)values(" + "'" + textBox9.Text + "'" + "," + "'" + textBox8.Text + "'" + "," + "'" + textBox5.Text + "'" + "," + "'" + textBox1.Text + "'" + "," + "Convert(Datetime,Convert(char(15),"+"'" + dateTimePicker2.Value +"'"+")" + "," + "'" + dateTimePicker1.Value.ToLongTimeString() + "'" + "," + "'" + "Active" + "'" + ")", conn);
cmd.ExecuteNonQuery();
4

1 回答 1

1

您应该始终使用参数化查询 - 这可以防止 SQL 注入攻击,提高性能,并避免将数据不必要地转换为字符串以将其插入数据库。

尝试这样的事情:

// define your INSERT query as string *WITH PARAMETERS*
string insertStmt = "INSERT into survey_Request1(sur_no, sur_custname, sur_address, sur_emp, sur_date, sur_time, Sur_status) VALUES(@Surname, @SurCustName, @SurAddress, @SurEmp, @SurDate, @SurTime, @SurStatus)";

// put your connection and command into "using" blocks
using(SqlConnection conn = new SqlConnection("-your-connection-string-here-"))
using(SqlCommand cmd = new SqlCommand(insertStmt, conn))
{
    // define parameters and supply values
    cmd.Parameters.AddWithValue("@Surname", textBox9.Text.Trim());
    cmd.Parameters.AddWithValue("@SurCustName", textBox8.Text.Trim());
    cmd.Parameters.AddWithValue("@SurAddress", textBox5.Text.Trim());
    cmd.Parameters.AddWithValue("@SurEmp", textBox1.Text.Trim());
    cmd.Parameters.AddWithValue("@SurDate", dateTimePicker2.Value.Date);
    cmd.Parameters.AddWithValue("@SurTime", dateTimePicker2.Value.Time);
    cmd.Parameters.AddWithValue("@SurStatus", "Active");

    // open connection, execute query, close connection again
    conn.Open();
    int rowsAffected = cmd.ExecuteNonQuery();
    conn.Close();
}

建议使用更具表现力的名称来命名您的文本框。textbox9并没有真正告诉我是哪个文本框 -textboxSurname更好

于 2013-04-17T14:38:12.990 回答