将dateTImePicker值转换为字符串

时间:2012-11-11 18:47:14

标签: c# .net sql string

我正在使用dateTimePicker从Windows窗体中的用户收集日期以插入SQL Server数据库但是当我调试它时,它说“connot将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");

2 个答案:

答案 0 :(得分:3)

您的代码容易受到SQL injection的攻击。我建议你使用参数化查询。同样在您的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类型,这样您就不需要进行任何字符串解析和日期操纵。

答案 1 :(得分: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