C# 数据库更新期间发生转换错误
我正在使用ASP.NET表单向SQL数据库输入当前日期。从字符串转换日期时间时转换失败。这是我正在使用的代码C# 数据库更新期间发生转换错误,c#,asp.net,date-conversion,C#,Asp.net,Date Conversion,我正在使用ASP.NET表单向SQL数据库输入当前日期。从字符串转换日期时间时转换失败。这是我正在使用的代码 txt_OrderDate.Text = DateTime.Now.ToShortDateString(); 这样做是危险的。建议改用Sql参数 这样使用它 DateTime dt=DateTime.ParseExact(txt_OrderDate.Text,“yyyy-MM-dd-HH:MM”,CultureInfo.InvariantCulture) 然后将dt值传递给SQL参数
txt_OrderDate.Text = DateTime.Now.ToShortDateString();
DateTime dt=DateTime.ParseExact(txt_OrderDate.Text,“yyyy-MM-dd-HH:MM”,CultureInfo.InvariantCulture)
如果txt_OrderDate.Text是字符串类型,并且看起来是这样,那么应该可以工作。您的错误一定发生在其他地方。您可以显示更多代码吗?更新您的问题以添加数据库insert/update codestring query9=“update Order_生产集交货_Date=”+“Convert.ToDateTime(TextBox11.Text.ToString())+“‘WHERE OP_ID=””+DropDownList1.SelectedItem.ToString()+“';”mainclass.Updates(查询9);为什么要执行Convert.ToDateTime?将日期作为字符串放在两个单引号内是有效的语法。TextBox11是否与txt_OrderDate相同?因为要求在将日期传递到数据库时将其转换为字符串,并且数据库中的数据类型为date。我删除了单引号,但它仍然给出了错误。我只想以日期格式插入数据。据我所知,您正在将其作为字符串传递到数据库。我是否正确?在数据库字段中,数据类型是datetime,而我是此处的传递字符串格式。如果您的格式不同,请提供您的格式。这是我需要SQL表来保存yyyy MM DDS的格式ql函数convert和您的查询将是(插入测试_日期值(convert(VARCHAR(10),“+TextBox1.Text+”,120)),con);DateTime dt=DateTime.ParseExact(txt_OrderDate.Text,“yyyy-MM-dd”,CultureInfo.InvariantCulture);这是可能的吗?我将yyyy-MM-dd HH:MM更改为yyyy-MM-dd?我不知道您的应用程序的默认区域性是什么,所以您必须尝试一下。实际上,这必须有效。
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();
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);
}
}
}