简体   繁体   English

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

[英]Error when inserting data into database with C#

When I try to insert a line in my database, I get the following error: Error当我尝试在我的数据库中插入一行时,出现以下错误:错误

This is the code:这是代码:

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;
}

First I thought the problem was the format of the date, but when I insert this line directly into the database through phpmyadmin, there is no problem.一开始以为是日期格式的问题,但是当我通过phpmyadmin直接把这行插入到数据库中时,就没有问题了。

Probably this is easy to solve, but I can't find the problem...可能这很容易解决,但我找不到问题...

Emphasize on parameterized queries:强调参数化查询:

Method 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!!");
    }
}

Method 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!!");
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM