MySqlDataReader: DataTable.Fill(reader) throws ConstraintException

纵饮孤独 提交于 2019-12-05 08:26:59

I had the same problem but got it fixed by using the workaround from this post: http://bugs.mysql.com/bug.php?id=65065 (at bottom):

cmd.CommandText = "SELECT cam.no_serie, t.mnt FROM trx t LEFT JOIN camn cam USING(id_camn) ";
    MySqlDataReader dr = cmd.ExecuteReader();
    DataSet ds = new DataSet();
    DataTable dataTable = new DataTable();
    ds.Tables.Add(dataTable);
    ds.EnforceConstraints = false;
    dataTable.Load(dr);
    dr.Close();

I just figured out, that

table.Fill(reader)

does not create the constraint, if I already added the columns.

So I fixed this by using a nice little extension method:

    public static void Load(this DataTable table, IDataReader reader, bool createColumns)
    {

        if (createColumns)
        {
            table.Columns.Clear();
            var schemaTable = reader.GetSchemaTable();
            foreach (DataRowView row in schemaTable.DefaultView)
            {
                var columnName = (string)row["ColumnName"];
                var type = (Type)row["DataType"];
                table.Columns.Add(columnName, type);
            }
        }

        table.Load(reader);
    }

Usage:

table.Fill(reader, true);

There is simple dirty way how to fix it - surround column in query with unique contraint with concat function:

var commandText = "SELECT CONCAT(o.orderno, ''), od.item, od.qty ...";

I had the same error today and want to share.My problem was a column with a LONGTEXT type. If I include LONGTEXT column in my query and tried to load dataset without specifying column names exception was thrown. Based on SchlaWiener's code I rewrote the code as follows and everything is fine now.

MySqlDataReader resultSet = cmd.ExecuteReader();
dt.Columns.Clear();
for (int i = 0; i < resultSet.FieldCount; i++)
{
    dt.Columns.Add(resultSet.GetName(i));
}
dt.Load(resultSet);

MySQL allows multiple null values in unique indexes. This causes ConstraintException on fill. How to fix: find this constraint in the 'table.Constraints' list and remove it or just clear all constraints.

I had a similar problem with the queries, when loading the Datatable () with the MYSQL Reader it generated error NON-NULL, UNIQUE or FOREIGN-KEY.

In the end I solved it by changing the MySQL Connector.NET version.

https://dev.mysql.com/downloads/connector/net/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!