草庐IT

c# - 从 gridview 插入数据时处理 'NULL' 和键约束

coder 2024-06-18 原文

我正在尝试通过 C# Windows 应用程序中的 gridview 将值插入到数据库中。我尝试了两种不同的方法,但似乎都不适合我。 2类代码如下所示......

假设,即使下面的代码有效......我收到关于主键和外键约束的各种错误......

问题:

  1. 我有 confactorIDmacroID 列作为整数,在目标 businesslogic 表中可以为空......我'我不确定如何通过 C# gridview 工具在这些列中插入“NULL”...

  2. 即使我将整数值作为输入,也似乎存在外键和主键(重复)约束问题....

我需要在下面的代码中更改什么才能解决这些问题......我已经被这些问题困扰了 8 个多小时......非常感谢任何帮助。

代码类型 1:

    private void ADD_button_Click(object sender, EventArgs e)
    {
        try
        {
            using (SqlConnection con = new SqlConnection(sqlconn))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.Connection = con;
                    con.Open();

                    for (int i = 1; i < dataGridView.Rows.Count; i++)
                    {
                        string sql = @"INSERT INTO " + schemaName +"ERSBusinessLogic VALUES ("
                                        + dataGridView.Rows[i].Cells["ERSBusinessLogic_ID"].Value + ", '"
                                        + dataGridView.Rows[i].Cells["ERSBusinessLogic_Formula"].Value.ToString() + "', "
                                        + dataGridView.Rows[i].Cells["ERSBusinessLogic_InputsCount"].Value + ",'"
                                        + dataGridView.Rows[i].Cells["ERSBusinessLogic_Inputs"].Value.ToString() + "', "
                                        + dataGridView.Rows[i].Cells["ERSBusinessLogic_ConvFactorID"].Value + ", "
                                        + dataGridView.Rows[i].Cells["ERSBusinessLogic_MacroID"].Value + ", '"
                                        + dataGridView.Rows[i].Cells["ERSBusinessLogic_DataSeries"].Value.ToString() + "', '"
                                        + dataGridView.Rows[i].Cells["ERSBusinessLogic_InputTimeDimensionValue"].Value.ToString() + "', "
                                        + dataGridView.Rows[i].Cells["ERSBusinessLogic_InputTimeDimensionType"].Value + ", "
                                        + dataGridView.Rows[i].Cells["ERSBusinessLogic_GeographyDimensionID"].Value + ", "
                                        + dataGridView.Rows[i].Cells["ERSBusinessLogic_InputsUnitsIDs"].Value + ", '"
                                        + dataGridView.Rows[i].Cells["ERSBusinessLogic_Type"].Value + "', "
                                        + dataGridView.Rows[i].Cells["ERSBusinessLogic_PrivacyID"].Value + ", '"
                                        + dataGridView.Rows[i].Cells["ERSBusinessLogic_LongDesc"].Value.ToString() + "', '"
                                        + dataGridView.Rows[i].Cells["ERSBusinessLogic_InputSources"].Value.ToString() + "', '"
                                        + dataGridView.Rows[i].Cells["ERSBusinessLogic_OutputName"].Value.ToString() + "', "
                                        + dataGridView.Rows[i].Cells["ERSBusinessLogic_OutputUnitID"].Value + ", '"
                                        + dataGridView.Rows[i].Cells["ERSBusinessLogic_OutputDestination"].Value.ToString() + "', '"
                                        + dataGridView.Rows[i].Cells["ERSBusinessLogic_OutputTimeDimensionValue"].Value.ToString() + "', "
                                        + dataGridView.Rows[i].Cells["ERSBusinessLogic_OutputTimeDimensionType"].Value + ", "
                                        + dataGridView.Rows[i].Cells["ERSBusinessLogic_GroupID"].Value + ");";

                         if ((dataGridView.Rows[i].Cells["ERSBusinessLogic_ConvFactorID"].Value == " ") && (dataGridView.Rows[i].Cells["ERSBusinessLogic_MacroID"].Value == null))
                         {
                             Convert.ToInt32(dataGridView.Rows[i].Cells["ERSBusinessLogic_ConvFactorID"].Value = "NULL");
                             Convert.ToInt32 (dataGridView.Rows[i].Cells["ERSBusinessLogic_MacroID"].Value = "NULL");

                             cmd.CommandText = sql;
                             cmd.ExecuteNonQuery();
                         }
                         else
                         {
                             cmd.CommandText = sql;
                             cmd.ExecuteNonQuery();
                         }
                     }
                 }
             }
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error : " + ex.Message);
        }
        finally
        {
            con.Close();
        }
    }

代码类型 2:

private void ADD_button_Click(object sender, EventArgs e)
{
    // Getting data from DataGridView
    DataTable myDt = new DataTable();
    myDt = GetDTfromDGV(dataGridView);

    // Writing to sql
    WriteToSQL(myDt);
}

private DataTable GetDTfromDGV(DataGridView dgv)
{
    // Making our DataTable
    DataTable dt = new DataTable();

    foreach (DataGridViewColumn column in dgv.Columns)
    {
        dt.Columns.Add(column.Name, typeof(string));
    }

    // Getting data
    foreach (DataGridViewRow dgvRow in dgv.Rows)
    {
        DataRow dr = dt.NewRow();

        for (int col = 0; col < dgv.Columns.Count; col++)
        {
            dr[col] = dgvRow.Cells[col].Value;
        }

        dt.Rows.Add(dr);
    }

    // removing empty rows
    for (int row = dt.Rows.Count - 1; row >= 0; row--)
    {
        bool flag = true;

        for (int col = 0; col < dt.Columns.Count; col++)
        {
            if (dt.Rows[row][col] != DBNull.Value)
            {
                flag = false;
                break;
            }
        }

        if (flag == true)
        {
            dt.Rows.RemoveAt(row);
        }
    }

    return dt;
}

private void WriteToSQL(DataTable dt)
{
    using (SqlConnection con = new SqlConnection(sqlconn))
    {
        SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con);
        // Setting the database table name
        sqlBulkCopy.DestinationTableName = "[AnimalProductsCoSD].[CoSD].[ERSBusinessLogic]";
        // Mapping the DataTable columns with that of the database table
        Convert.ToInt32 (sqlBulkCopy.ColumnMappings.Add(dt.Columns[0].ColumnName, "ERSBusinessLogic_ID"));
       Convert.ToString(sqlBulkCopy.ColumnMappings.Add(dt.Columns[1].ColumnName, "ERSBusinessLogic_Formula"));
       Convert.ToInt32 (sqlBulkCopy.ColumnMappings.Add(dt.Columns[2].ColumnName, "ERSBusinessLogic_InputsCount"));
        Convert.ToString (sqlBulkCopy.ColumnMappings.Add(dt.Columns[3].ColumnName, "ERSBusinessLogic_Inputs"));
        Convert.ToInt32 (sqlBulkCopy.ColumnMappings.Add(dt.Columns[4].ColumnName, "ERSBusinessLogic_ConvFactorID"));
        Convert.ToInt32 (sqlBulkCopy.ColumnMappings.Add(dt.Columns[5].ColumnName, "ERSBusinessLogic_MacroID"));

        Convert.ToString (sqlBulkCopy.ColumnMappings.Add(dt.Columns[6].ColumnName, "ERSBusinessLogic_DataSeries"));
        Convert.ToString (sqlBulkCopy.ColumnMappings.Add(dt.Columns[7].ColumnName, "ERSBusinessLogic_InputTimeDimensionValue"));
        Convert.ToInt32 (sqlBulkCopy.ColumnMappings.Add(dt.Columns[8].ColumnName, "ERSBusinessLogic_InputTimeDimensionType"));
        Convert.ToInt32 (sqlBulkCopy.ColumnMappings.Add(dt.Columns[9].ColumnName, "ERSBusinessLogic_GeographyDimensionID"));
        Convert.ToInt32 (sqlBulkCopy.ColumnMappings.Add(dt.Columns[10].ColumnName, "ERSBusinessLogic_InputsUnitsIDs"));
        Convert.ToString (sqlBulkCopy.ColumnMappings.Add(dt.Columns[11].ColumnName, "ERSBusinessLogic_Type"));

        Convert.ToInt32 (sqlBulkCopy.ColumnMappings.Add(dt.Columns[12].ColumnName, "ERSBusinessLogic_PrivacyID"));
        Convert.ToString (sqlBulkCopy.ColumnMappings.Add(dt.Columns[13].ColumnName, "ERSBusinessLogic_LongDesc"));
        Convert.ToString (sqlBulkCopy.ColumnMappings.Add(dt.Columns[14].ColumnName, "ERSBusinessLogic_InputSources"));
        Convert.ToString (sqlBulkCopy.ColumnMappings.Add(dt.Columns[15].ColumnName, "ERSBusinessLogic_OutputName"));
        Convert.ToInt32 (sqlBulkCopy.ColumnMappings.Add(dt.Columns[16].ColumnName, "ERSBusinessLogic_OutputUnitID"));
        Convert.ToString (sqlBulkCopy.ColumnMappings.Add(dt.Columns[17].ColumnName, "ERSBusinessLogic_OutputDestination"));

        Convert.ToString (sqlBulkCopy.ColumnMappings.Add(dt.Columns[18].ColumnName, "ERSBusinessLogic_OutputTimeDimensionValue"));
        Convert.ToInt32 (sqlBulkCopy.ColumnMappings.Add(dt.Columns[19].ColumnName, "ERSBusinessLogic_OutputTimeDimensionType"));
        Convert.ToInt32 (sqlBulkCopy.ColumnMappings.Add(dt.Columns[20].ColumnName, "ERSBusinessLogic_GroupID"));

        con.Open();
        sqlBulkCopy.WriteToServer(dt);
    }
}

谢谢

最佳答案

首先检查您的数据库表,保留来自其他表的 ID 的列必须允许空值,如下所示:

而且如果你的表ID是自增的Identity列你不需要写ID,表会自动添加ID。

如果一切正常,那么尝试这样做:

private DataTable GetDTfromDGV(DataGridView dgv)
    {
        // Macking our DataTable
        DataTable dt = new DataTable();
        //Another way to add columns
        dt.Columns.AddRange(new DataColumn[5]
            {
                //new DataColumn("table_ID", typeof(string)), if table_ID is not Identity column with auto increment then uncomment
                new DataColumn("sql_col2", typeof(string)),
                new DataColumn("sql_col3", typeof(string)),
                new DataColumn("sql_col4", typeof(string)),
                new DataColumn("Table_2_ID", typeof(int)),
                new DataColumn("Table_3_IDt", typeof(int))
            });
        // Getting data
        foreach (DataGridViewRow dgvRow in dgv.Rows)
        {
            DataRow dr = dt.NewRow();
            for (int col = 1; col < dgv.Columns.Count; col++) //if table_ID is not Identity column with auto increment then start with 0
            {
                dr[col - 1] = dgvRow.Cells[col].Value == null ? DBNull.Value : dgvRow.Cells[col].Value;
            }
            dt.Rows.Add(dr);
        }
        // removing empty rows
        ....
        return dt;
    }
    private void WriteToSQL(DataTable dt)
    {
        string connectionStringSQL = "Your connection string";
        using (SqlConnection sqlConn = new SqlConnection(connectionStringSQL))
        {
            SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(sqlConn);
            // Setting the database table name
            sqlBulkCopy.DestinationTableName = "Table_1";
            // Mapping the DataTable columns with that of the database table
            //sqlBulkCopy.ColumnMappings.Add(dt.Columns[0].ColumnName, "table_ID"); table_ID is Identity column with auto increment
            sqlBulkCopy.ColumnMappings.Add(dt.Columns[0].ColumnName, "sql_col2");
            sqlBulkCopy.ColumnMappings.Add(dt.Columns[1].ColumnName, "sql_col3");
            sqlBulkCopy.ColumnMappings.Add(dt.Columns[2].ColumnName, "sql_col4");
            sqlBulkCopy.ColumnMappings.Add(dt.Columns[3].ColumnName, "Table_2_ID");
            sqlBulkCopy.ColumnMappings.Add(dt.Columns[4].ColumnName, "Table_3_ID");
            sqlConn.Open();
            sqlBulkCopy.WriteToServer(dt);
        }
    }

我试过了,这就是我得到的:

关于c# - 从 gridview 插入数据时处理 'NULL' 和键约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36291220/

有关c# - 从 gridview 插入数据时处理 'NULL' 和键约束的更多相关文章

  1. ruby-on-rails - rails : "missing partial" when calling 'render' in RSpec test - 2

    我正在尝试测试是否存在表单。我是Rails新手。我的new.html.erb_spec.rb文件的内容是:require'spec_helper'describe"messages/new.html.erb"doit"shouldrendertheform"dorender'/messages/new.html.erb'reponse.shouldhave_form_putting_to(@message)with_submit_buttonendendView本身,new.html.erb,有代码:当我运行rspec时,它失败了:1)messages/new.html.erbshou

  2. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

    我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

  3. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  4. ruby - 如何指定 Rack 处理程序 - 2

    Rackup通过Rack的默认处理程序成功运行任何Rack应用程序。例如:classRackAppdefcall(environment)['200',{'Content-Type'=>'text/html'},["Helloworld"]]endendrunRackApp.new但是当最后一行更改为使用Rack的内置CGI处理程序时,rackup给出“NoMethodErrorat/undefinedmethod`call'fornil:NilClass”:Rack::Handler::CGI.runRackApp.newRack的其他内置处理程序也提出了同样的反对意见。例如Rack

  5. ruby-on-rails - Rails 3.2.1 中 ActionMailer 中的未定义方法 'default_content_type=' - 2

    我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer

  6. ruby - 在 jRuby 中使用 'fork' 生成进程的替代方案? - 2

    在MRIRuby中我可以这样做:deftransferinternal_server=self.init_serverpid=forkdointernal_server.runend#Maketheserverprocessrunindependently.Process.detach(pid)internal_client=self.init_client#Dootherstuffwithconnectingtointernal_server...internal_client.post('somedata')ensure#KillserverProcess.kill('KILL',

  7. ruby - 主要 :Object when running build from sublime 的未定义方法 `require_relative' - 2

    我已经从我的命令行中获得了一切,所以我可以运行rubymyfile并且它可以正常工作。但是当我尝试从sublime中运行它时,我得到了undefinedmethod`require_relative'formain:Object有人知道我的sublime设置中缺少什么吗?我正在使用OSX并安装了rvm。 最佳答案 或者,您可以只使用“require”,它应该可以正常工作。我认为“require_relative”仅适用于ruby​​1.9+ 关于ruby-主要:Objectwhenrun

  8. ruby - 无法让 RSpec 工作—— 'require' : cannot load such file - 2

    我花了三天的时间用头撞墙,试图弄清楚为什么简单的“rake”不能通过我的规范文件。如果您遇到这种情况:任何文件夹路径中都不要有空格!。严重地。事实上,从现在开始,您命名的任何内容都没有空格。这是我的控制台输出:(在/Users/*****/Desktop/LearningRuby/learn_ruby)$rake/Users/*******/Desktop/LearningRuby/learn_ruby/00_hello/hello_spec.rb:116:in`require':cannotloadsuchfile--hello(LoadError) 最佳

  9. ruby-on-rails - 新 Rails 项目 : 'bundle install' can't install rails in gemfile - 2

    我已经像这样安装了一个新的Rails项目:$railsnewsite它执行并到达:bundleinstall但是当它似乎尝试安装依赖项时我得到了这个错误Gem::Ext::BuildError:ERROR:Failedtobuildgemnativeextension./System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/bin/rubyextconf.rbcheckingforlibkern/OSAtomic.h...yescreatingMakefilemake"DESTDIR="cleanmake"DESTDIR="

  10. ruby-on-rails - rspec should have_select ('cars' , :options => ['volvo' , 'saab' ] 不工作 - 2

    关闭。这个问题需要detailsorclarity.它目前不接受答案。想改进这个问题吗?通过editingthispost添加细节并澄清问题.关闭8年前。Improvethisquestion在首页我有:汽车:VolvoSaabMercedesAudistatic_pages_spec.rb中的测试代码:it"shouldhavetherightselect"dovisithome_pathit{shouldhave_select('cars',:options=>['volvo','saab','mercedes','audi'])}end响应是rspec./spec/request

随机推荐