数据导入OpenFileDialog

来源:互联网 发布:js prompt函数返回值 编辑:程序博客网 时间:2024/06/06 05:20

导入文件:张三|40    捷克俊逸|27     罗布特|32  以1.txt形式保存

  private void btnImport_Click(object sender, EventArgs e)        {            OpenFileDialog ofd = new OpenFileDialog();            ofd.Filter = "文本文件|*.txt";            if (ofd.ShowDialog()!=DialogResult.OK)            {                return;            }            string filename = ofd.FileName;            //ReadAllLines是把文件一次读取到string集合中            IEnumerable<string> lines=File.ReadAllLines(filename);            foreach (string line in lines)            {                string[] str = line.Split('|');                string name = str[0];                string age = str[1];                            //插入数据库操作            string strconn = "Data Source=.\\SQLEXPRESS;Initial Catalog=My_Test;Integrated Security=True";            SqlConnection conn = new SqlConnection(strconn);            conn.Open();            string strSql = "insert into T_table1(name,age) values ('"+name+"','"+Convert .ToInt32(age)+"')";                                    SqlCommand cmd = new SqlCommand(strSql ,conn);            if (cmd.ExecuteNonQuery() > 0)            {                MessageBox.Show("数据导入成功!");            }            else            {                MessageBox.Show("数据导入失败!");            }            }        }


 


  
 
                

原创粉丝点击