【SQL Server】批量数据导入到数据库

来源:互联网 发布:淘宝高佣金采集 编辑:程序博客网 时间:2024/05/01 18:42

应用场景

  在txt文件中有很多行用户数据,包括用户名和密码,中间用竖线隔开。如图所示。用界面化的方式,将其全部导入到数据库登录表中。

实现代码

private void btnOpen_Click(object sender, EventArgs e){    OpenFileDialog of = new OpenFileDialog();    //MessageBox.Show(of.ShowDialog().ToString());    if (of.ShowDialog() == DialogResult.OK)    {        txtImport.Text = of.FileName;    }}private void btnBegin_Click(object sender, EventArgs e){    if (string.IsNullOrEmpty(txtImport.Text))    {        MessageBox.Show("请选择文件");    }    else    {        //检查文件是否是txt,文件是否存在        //File.Exists();检查是否存在        string[] alllines = File.ReadAllLines(txtImport.Text, Encoding.Default);        //MessageBox.Show(alllines[0]);        //从一个数组里面一个一个往外面取,每循环一次就赋值给item        foreach (string item in alllines)        {            string[] nameandpwd = item.Split('|');            //Console.WriteLine(nameandpwd[0] + "   " + nameandpwd[1]);            SqlHelper.Insert(nameandpwd[0], nameandpwd[1]);        }        MessageBox.Show("导入完毕!");    }}
class SqlHelper{    public static bool Insert(string name, string pwd)    {        using (SqlConnection conn = new SqlConnection("server=.;database=Test;uid=sa;pwd=jujianfei"))        {            string sql = "insert into Login values(@name,@pwd)";            SqlCommand cmd = new SqlCommand(sql, conn);            SqlParameter sp1 = new SqlParameter("@name", name);            SqlParameter sp2 = new SqlParameter("@pwd", pwd);            cmd.Parameters.Add(sp1);            cmd.Parameters.Add(sp2);            conn.Open();            return cmd.ExecuteNonQuery() > 0;        }    }}

效果展示

这里写图片描述 这里写图片描述

1 0
原创粉丝点击