0

我正在使用 dateTimePicker 从 Windows 表单中的用户收集日期以插入 SQL Server 数据库但是当我调试它时它说“不能将 dateTime 转换为字符串”这是代码

string Agent = FieldAgentCombo.Text;
            string Query = "INSERT INTO Comittment(Date,Field_Staff_Date,Detail,Priority,company_name,Name) values('" + Client + "','" + Agent + "','" + Date + "','" + FieldStaffDate + "','" + Detail + "','" + Priority + "')";

            SqlCommand cmd = new SqlCommand(Query, conn);

            int status = cmd.ExecuteNonQuery();
            if (status > 0)
                MessageBox.Show("record inserted");
4

2 回答 2

3

您的代码容易受到SQL 注入的攻击。我建议您使用参数化查询。同样在您的 SQL 查询中,您似乎混合了参数。确保它们匹配。例如:

// load the values that you want to insert into standard .NET types
DateTime date = ...
DateTime fieldStaffDate = ...
string detail = ...
string priority = ...
string companyName = ...
string name = ...

// now connect to the database to execute the SQL query
using (var conn = new SqlConnection(ConnectionString))
using (var cmd = conn.CreateCommand())
{
    conn.Open();
    cmd.CommandText = 
    @"INSERT INTO Comittment(
          Date, 
          Field_Staff_Date, 
          Detail, 
          Priority, 
          company_name, 
          Name) 
      VALUES (
          @Date, 
          @Field_Staff_Date, 
          @Detail, 
          @Priority, 
          @company_name, 
          @name)";

    cmd.Parameters.AddWithValue("@Date", date);
    cmd.Parameters.AddWithValue("@Field_Staff_Date", fieldStaffDate);
    cmd.Parameters.AddWithValue("@Detail", detail);
    cmd.Parameters.AddWithValue("@Priority", priority);
    cmd.Parameters.AddWithValue("@company_name", companyName);
    cmd.Parameters.AddWithValue("@name", name);

    cmd.ExecuteNonQuery();
}

这样,查询就不再容易受到 SQL 注入的攻击,此外,ADO.NET 还将负责将 .NET 类型正确格式化为相应的 SQL 类型,这样您就不需要进行任何字符串解析和日期操作.

于 2012-11-11T18:54:01.337 回答
0

如果要将当前日期插入sql,而不是进行转换,只需now()直接添加到查询

除此之外,请查看此链接:http ://www.csharp-examples.net/string-format-datetime/

// create date time 2008-03-09 16:05:07.123
DateTime dt = new DateTime(2008, 3, 9, 16, 5, 7, 123);

String.Format("{0:y yy yyy yyyy}", dt);  // "8 08 008 2008"   year
String.Format("{0:M MM MMM MMMM}", dt);  // "3 03 Mar March"  month
String.Format("{0:d dd ddd dddd}", dt);  // "9 09 Sun Sunday" day
String.Format("{0:h hh H HH}",     dt);  // "4 04 16 16"      hour 12/24
String.Format("{0:m mm}",          dt);  // "5 05"            minute
String.Format("{0:s ss}",          dt);  // "7 07"            second
String.Format("{0:f ff fff ffff}", dt);  // "1 12 123 1230"   sec.fraction
String.Format("{0:F FF FFF FFFF}", dt);  // "1 12 123 123"    without zeroes
String.Format("{0:t tt}",          dt);  // "P PM"            A.M. or P.M.
String.Format("{0:z zz zzz}",      dt);  // "-6 -06 -06:00"   time zone
于 2012-11-11T18:52:08.350 回答