• [ADO.NET]写入数据


    关键字:.NET,SQL SERVER,SQLBULKCOPY

    插入一条数据的操作(SqlCmd)。

    public void InsertOneIntoSourceDB()
    {            
        if (DBConnection(GetConnectionString()))
        {
            string sqlinsert = null;
            SqlTransaction tran = con.BeginTransaction();
            SqlCommand cmd = con.CreateCommand();
            cmd.Transaction = tran;
            try
            {
                sqlinsert = "insert into MeterMeasureHistories values(@meterMeasureID,@value,@quality,@timestamp)";
                cmd.CommandText = sqlinsert;
                SqlParameter[] parameters = new SqlParameter[]
                    {
                        new SqlParameter("@meterMeasureID",SqlDbType.Int){Value = 133},
                        new SqlParameter("@value",SqlDbType.Float){Value = 0},
                        new SqlParameter("@quality",SqlDbType.NVarChar){Value = "good"}, 
                        new SqlParameter("@timestamp",SqlDbType.DateTime){Value = DateTime.Now}
                    };
                cmd.Parameters.AddRange(parameters);
                cmd.ExecuteNonQuery();
                tran.Commit();
            }
            catch (Exception e)
            {
                throw e;
            }
            DBShutdown();
        }
    }

    插入多条数据,利用了SqlBulkCopy、DataTable、DataRow,效率比循环高(SqlDataAdapter)。

    public void InsertIntoSourceDB()
    {
        if (DBConnection(GetConnectionString()))
        {
            try
            {
                DataTable dt = new DataTable();
                dt.Columns.AddRange(new DataColumn[] 
                { 
                    new DataColumn("MeterMeasureHistoryID"), 
                    new DataColumn("MeterMeasureID"), 
                    new DataColumn("Value"), 
                    new DataColumn("Quality"), 
                    new DataColumn("Timestamp")
                });
                foreach (var item in meterMeasureHistories)
                {
                    DataRow dr = dt.NewRow();
                    dr[1] = item.MeterMeasureID;
                    dr[2] = item.Value;
                    dr[3] = item.Quality;
                    dr[4] = item.Timestamp;
                    dt.Rows.Add(dr);
                }
                SqlBulkCopy bulkcopy = new SqlBulkCopy(con);
                bulkcopy.DestinationTableName = "dbo.MeterMeasureHistories";
                bulkcopy.WriteToServer(dt);
            }
            catch (Exception e)
            {
                throw e;
            }
            DBShutdown();
        }
    }
  • 相关阅读:
    GitLab 介绍
    git 标签
    git 分支
    git 仓库 撤销提交 git reset and 查看本地历史操作 git reflog
    git 仓库 回退功能 git checkout
    python 并发编程 多进程 练习题
    git 命令 查看历史提交 git log
    git 命令 git diff 查看 Git 区域文件的具体改动
    POJ 2608
    POJ 2610
  • 原文地址:https://www.cnblogs.com/belloworld/p/5210444.html
Copyright © 2020-2023  润新知