Hi I am new in this forum. its my first post so if I made something wrong... I have the code below. I am receiving the error
"conversion failed when converting date and/or time from character string. visual studio"
public void pay_fighter(string FighterID, string PaymentDay, string PaymentAmount, string PaymentDescr)
{
if (FighterID.Length != 0)
{
if (conn.State.ToString() == "Closed")
{
conn.Open();
}
SqlCommand newCmd = conn.CreateCommand();
newCmd.Connection = conn;
newCmd.CommandType = CommandType.Text;
newCmd.Parameters.AddWithValue("PaymentAmount", PaymentAmount);
newCmd.Parameters.AddWithValue("PaymentDescr", PaymentDescr);
newCmd.CommandText = "INSERT INTO PaymentInfo VALUES('" + FighterID + "','" + PaymentDay + "',@PaymentAmount, @PaymentDescr)";
newCmd.ExecuteNonQuery();
}
}
Use correct types and SqlParameters for all parameters in the query.
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();
}
}
Will be more safe to create new SqlConnection instance for query. ADO.NET will handle actual/physical connections and re-use already created if needed.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.