在 SQL Server 2005 datetime c# 中插入日期和时间时出错? [英] Error inserting date and time in SQL Server 2005 datetime c#?

查看:52
本文介绍了在 SQL Server 2005 datetime c# 中插入日期和时间时出错?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

保存到 SQL Server 2005 的问题:

Problem saving to 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();

推荐答案

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

You should ALWAYS use parametrized queries - this prevents SQL injection attacks, is better for performance, and avoids unnecessary conversions of data to strings just to insert it into the database.

尝试这样的事情:

// 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好多更好!

It would also be advisable to name your textboxes with more expressive names. textbox9 doesn't really tell me which textbox that is - textboxSurname would be MUCH better!

这篇关于在 SQL Server 2005 datetime c# 中插入日期和时间时出错?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆