C# Visual Studio错误:从字符串转换日期和/或时间时转换失败
嗨,我是这个论坛的新成员。这是我的第一篇帖子,所以如果我做错了什么。。。 我有下面的代码。我收到了错误 从字符串转换日期和/或时间时,转换失败。visual studioC# Visual Studio错误:从字符串转换日期和/或时间时转换失败,c#,sql,sql-server,C#,Sql,Sql Server,嗨,我是这个论坛的新成员。这是我的第一篇帖子,所以如果我做错了什么。。。 我有下面的代码。我收到了错误 从字符串转换日期和/或时间时,转换失败。visual studio 对查询中的所有参数使用正确的类型和SqlParameters public void pay_fighter( string fighterID, DateTime paymentDay, decimal paymentAmount, string paymentDescr) {
对查询中的所有参数使用正确的类型和SqlParameters
public void pay_fighter(
string fighterID,
DateTime paymentDay,
decimal paymentAmount,
string paymentDescr)
{
if (String.IsNullOrEmpty(fighterId))
{
return;
}
var query =
@"INSERT INTO PaymentInfo VALUES (
@FighterId,
@PaymentDay,
@PaymentAmount,
@PaymentDescr)";
var parameters = new[]
{
new SqlParameter
{
ParameterName = "@FigtherId",
SqlDbType = SqlDbType.Int, // use correct type for column
Value = fighterId
},
new SqlParameter
{
ParameterName = "@PaymentDay",
SqlDbType = SqlDbType.DateTime, // use correct date type defined in column
Value = paymentDay
},
new SqlParameter
{
ParameterName = "@PaymentAmount",
SqlDbType = SqlDbType.Decimal, // use correct type for column
Value = paymentAmount
},
new SqlParameter
{
ParameterName = "@PaymentDescr",
SqlDbType = SqlDbType.VarChar, // use correct type for column
Size = 100, // use size defined for column
Value = paymentDescr
}
};
using (var connection = new SqlConnection(connectionString))
using (var command = new SqlCommand(query, connection))
{
command.Parameters.AddRange(parameters);
connection.Open();
command.ExecuteNonQuery();
}
}
为查询创建新的SqlConnection实例将更安全。ADO.NET将处理实际/物理连接,并在需要时重用已创建的连接。是SQL Server还是MySQL?请避免标记垃圾邮件。请在PaymentInfo table.Ah中发布列的数据类型。严格类型的代码。您知道VB.Net和SQL Server都有专为保存日期时间数据而设计的数据类型,而您在这里根本不使用它们?为什么每个输入参数都是字符串?
public void pay_fighter(
string fighterID,
DateTime paymentDay,
decimal paymentAmount,
string paymentDescr)
{
if (String.IsNullOrEmpty(fighterId))
{
return;
}
var query =
@"INSERT INTO PaymentInfo VALUES (
@FighterId,
@PaymentDay,
@PaymentAmount,
@PaymentDescr)";
var parameters = new[]
{
new SqlParameter
{
ParameterName = "@FigtherId",
SqlDbType = SqlDbType.Int, // use correct type for column
Value = fighterId
},
new SqlParameter
{
ParameterName = "@PaymentDay",
SqlDbType = SqlDbType.DateTime, // use correct date type defined in column
Value = paymentDay
},
new SqlParameter
{
ParameterName = "@PaymentAmount",
SqlDbType = SqlDbType.Decimal, // use correct type for column
Value = paymentAmount
},
new SqlParameter
{
ParameterName = "@PaymentDescr",
SqlDbType = SqlDbType.VarChar, // use correct type for column
Size = 100, // use size defined for column
Value = paymentDescr
}
};
using (var connection = new SqlConnection(connectionString))
using (var command = new SqlCommand(query, connection))
{
command.Parameters.AddRange(parameters);
connection.Open();
command.ExecuteNonQuery();
}
}