c# 一次性插入多条数据

12 篇文章 0 订阅
c# 一次性插入多条数据
private void Form1_Load(object sender, EventArgs e)
        {
            DataTable dt = new DataTable();
            using (SqlConnection conn = new SqlConnection("Server=.;database=northwind;uid=sa"))
            {
                SqlDataAdapter sda = new SqlDataAdapter("Select top 5 * from Employees", conn);
                sda.Fill(dt);
            }
            dataGridView1.DataSource = dt;

        }

        public bool ExecuteNone(string[] sql)
        {
            bool result;
            SqlConnection conn = new SqlConnection("Server=.;database=tempdb;uid=sa;pwd=;");
            conn.Open();
            SqlTransaction tran = conn.BeginTransaction();
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            cmd.Transaction = tran;

            try
            {
                for (int i = 0; i < sql.Length; i++)
                {
                    if (sql[i] == null || sql[i] == "")
                    {
                        continue;
                    }
                    cmd.CommandText = sql[i];
                    cmd.ExecuteNonQuery();
                }
                tran.Commit();
                result = true;

            }

            catch (System.Exception)
            {
                tran.Rollback();
                result = false;
            }
            conn.Close();

            return result;

        }

        private void button1_Click(object sender, EventArgs e)
        {
            string[] sql = new string[dataGridView1.Rows.Count];
            int index = 0;
            foreach (DataGridViewRow gvr in dataGridView1.Rows)
            {
                if (gvr.Cells[0].Value == null)
                {
                    continue;
                }
                sql[index] = "INSERT INTO EmployeesCopy (employeeid,firstname,lastname) VALUES (" + gvr.Cells[0].Value + ",'" + gvr.Cells[1].Value + "','" + gvr.Cells[2].Value + "')";
                index++;
            }
            if (ExecuteNone(sql))
            {
                MessageBox.Show("插入成功!");
            }
            else
            {
                MessageBox.Show("插入失败!");
            }
        }

//就可以说是多条插入的例子了。你鉴赏鉴赏!!
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值