日期:2014-05-17 浏览次数:20816 次
//文件导入 private void button1_Click(object sender, EventArgs e) { if (openFileDialog1.ShowDialog() != DialogResult.OK) { return; } using (FileStream fileStream = File.OpenRead(openFileDialog1.FileName)) { using (StreamReader streamReader = new StreamReader(fileStream)) { using (SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=F:\C#工作文件夹\TestDemo\文件导入导出\文件导入导出\Database1.mdf;Integrated Security=True;User Instance=True")) { conn.Open(); using (SqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = "insert into T_xiaoli (Name,Num) values (@Name,@Num)"; string line = ""; while ((line = streamReader.ReadLine()) != null) { string[] str = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); string name = str[0]; int num = Convert.ToInt32(str[1]); cmd.Parameters.Clear();//将cmd的参数清空,避免参数重复追加到尾,出错 cmd.Parameters.Add(new SqlParameter("Name", name)); cmd.Parameters.Add(new SqlParameter("Num", num)); cmd.ExecuteNonQuery(); } } } } } MessageBox.Show("导入成功!"); }