• C#里如何把一个DataTable的数据追加进数据库里的某个表


    方法一

    DataTable table = new DataTable();
                //TODO: init table...
                string connStr = "user id=" + dbInfo.UserName + ";data source=" + dbInfo.DBServerIP + ";persist security info=False;initial catalog=" + dbInfo.DatabaseName + ";password=" + dbInfo.Password;
                SqlConnection conn = new SqlConnection(connStr);
                conn.Open();
                SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(conn);
                sqlBulkCopy.DestinationTableName = dbInfo.TableName;
                sqlBulkCopy.WriteToServer(table);
                sqlBulkCopy.Close();

    方法二

    DataTable table = new DataTable();
                //TODO: init table...
    
                string connStr = "user id=" + dbInfo.UserName + ";data source=" + dbInfo.DBServerIP + ";persist security info=False;initial catalog=" + dbInfo.DatabaseName + ";password=" + dbInfo.Password;
                DataTable dt = new DataTable();
                SqlConnection conn = new SqlConnection(connStr);
                SqlCommand cmd = new SqlCommand(string.Format("select * from {0} where 1=2", dbInfo.TableName), conn);
                SqlDataAdapter sda = new SqlDataAdapter(cmd);
                SqlCommandBuilder Builder = new SqlCommandBuilder(sda);
                sda.Fill(dt);
    
                DataRow addRow = null;
                foreach (DataRow row in table.Rows)
                {
                    addRow = dt.NewRow();
                    for (int i = 0; i < table.Columns.Count; i++)
                    {
                        addRow[i] = row[i];
                    }
                    dt.Rows.Add(addRow);
                }
    
                sda.Update(dt);


    总结

    1. 仅仅有 Insert ? 那么用 SqlBulkCopy.
    2. Insert/Update/Delete ? 那么用 DataAdapter.Update.


  • 相关阅读:
    OnWndMsg处理功能
    SpringMVC Ajax返回的请求json 的方式来解决在中国字符串乱码问题
    【Shell剧本练习】得出的结论是当前用户
    C++指针和引用简介
    HDU 3126 Nova [2009 Asia Wuhan Regional Contest Online]
    工作过程的编译器
    ubuntu selinux
    Maven创建工程 WEB
    Weblogic集群
    Dubbo
  • 原文地址:https://www.cnblogs.com/mfmdaoyou/p/6963988.html
Copyright © 2020-2023  润新知