使用C#将数据插入数据库时​​出错

时间:2018-02-15 17:40:30

标签: c# mysql odbc mariadb

当我尝试在数据库中插入一行时,出现以下错误: Error

这是代码:

try
{
    DateTime date = new DateTime(2018, 02, 15, 07, 06, 00);

    using (OdbcConnection con = new OdbcConnection(Properties.Settings.Default.ConnectionString))
    {
        OdbcCommand cmd = new OdbcCommand("INSERT INTO Kassatickets (id, datum, korting, totaal) VALUES 3, '2018-02-15 07:06:00', " + kt.KortingId + ", " + kt.Totaal, con);                 

        con.Open();
        if (cmd.ExecuteNonQuery() == 0)
        {
            throw new Exception("Er zijn geen wijzigingen uitgevoerd!!");
        }
    }
}
catch (Exception e)
{
    throw e;
}

首先我认为问题是日期的格式,但是当我通过phpmyadmin将此行直接插入数据库时​​,没有问题。

这可能很容易解决,但我找不到问题......

1 个答案:

答案 0 :(得分:1)

强调参数化查询:

方法1:

using (OdbcConnection con = new OdbcConnection(Properties.Settings.Default.ConnectionString))
{
    var query ="INSERT INTO Kassatickets (id, datum, korting, totaal) VALUES (?, ?, ?, ?)";     

    OdbcCommand cmd = new OdbcCommand(query, con);

    cmd.Parameters.Add("id", OdbcType.UniqueIdentifier).Value = 3;
    cmd.Parameters.Add("datum", OdbcType.VarChar).Value = "2018-02-15 07:06:00";
    cmd.Parameters.Add("korting", OdbcType.VarChar).Value = kt.KortingId;
    cmd.Parameters.Add("totaal", OdbcType.VarChar).Value = kt.Totaal;
    con.Open();
    if (cmd.ExecuteNonQuery() == 0)
    {
        throw new Exception("Er zijn geen wijzigingen uitgevoerd!!");
    }
}

方法2:

using (OdbcConnection con = new OdbcConnection(Properties.Settings.Default.ConnectionString))
{
    var query = "INSERT INTO Kassatickets (id, datum, korting, totaal) VALUES (@id, @datum, @korting, @totaal)";

    OdbcCommand cmd = new OdbcCommand(query, con);
    cmd.Parameters.AddWithValue("@id", 3);
    cmd.Parameters.AddWithValue("@datum", "2018-02-15 07:06:00");
    cmd.Parameters.AddWithValue("@korting", kt.KortingId);
    cmd.Parameters.AddWithValue("@totaal", kt.Totaal);
    con.Open();
    if (cmd.ExecuteNonQuery() == 0)
    {
        throw new Exception("Er zijn geen wijzigingen uitgevoerd!!");
    }
}