数据库更新期间的转换错误

时间:2014-10-30 03:50:57

标签: c# asp.net date-conversion

我使用ASP.NET表单将当前日期输入SQL数据库。从字符串转换日期时间时转换失败。这是我正在使用的代码。

txt_OrderDate.Text = DateTime.Now.ToShortDateString();

2 个答案:

答案 0 :(得分:1)

    SqlConnection con = new SqlConnection(@"Data Source=BG9;Initial Catalog=Northwind;Integrated Security=True");
    con.Open();
    SqlDataAdapter ad1 = new SqlDataAdapter();
    ad1.InsertCommand = new SqlCommand("insert into test_date values (CONVERT(VARCHAR(10),'" + TextBox1.Text+"',120))", con);
    ad1.InsertCommand.ExecuteNonQuery();
    con.Close();

答案 1 :(得分:1)

  1. 这是一种危险的方式。建议改为使用Sql参数。
  2. 以这种方式使用。

    DateTime dt = DateTime.ParseExact(txt_OrderDate.Text," yyyy-MM-dd HH:mm",CultureInfo.InvariantCulture);

  3. 然后将dt值传递给SQL参数。

  4. 从MSDN使用Sql参数的示例:

    private static void UpdateDemographics(Int32 customerID,             string demoXml,string connectionString)         {             //更新存储的商店的受众特征             //在xml列中。             string commandText =" UPDATE Sales.Store SET Demographics = @demographics"                 +" WHERE CustomerID = @ID;&#34 ;;

        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            SqlCommand command = new SqlCommand(commandText, connection);
            command.Parameters.Add("@ID", SqlDbType.Int);
            command.Parameters["@ID"].Value = customerID;
    
            // Use AddWithValue to assign Demographics.
            // SQL Server will implicitly convert strings into XML.
            command.Parameters.AddWithValue("@demographics", demoXml);
    
            try
            {
                connection.Open();
                Int32 rowsAffected = command.ExecuteNonQuery();
                Console.WriteLine("RowsAffected: {0}", rowsAffected);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }