- namespace 数据导入数据库
- {
- public partial class Form1 : Form
- {
- public Form1()
- {
- InitializeComponent();
- }
- private void button1_Click(object sender, EventArgs e)
- {
- if (openFileDialog1.ShowDialog() == DialogResult.OK)
- {
- using (FileStream filestream = File.OpenRead(openFileDialog1.FileName))
- {
- using (StreamReader streamreader = new StreamReader(filestream))
- {
- string line = null;
- while ((line = streamreader.ReadLine()) != null)
- {
- string[] strs = line.Split('|');
- string name = strs[0];
- int age = Convert.ToInt32(strs[1]);
- using (SqlConnection conn = new SqlConnection(@"Data Source=./SQLEXPRESS;
- AttachDBFilename=D:/My Documents/Documents/Visual Studio 2010/Projects/数据导入数据库/数据导入数据库/Database1.mdf;
- Integrated Security=True;User Instance=True"))
- {
- conn.Open();
- using (SqlCommand cmd = conn.CreateCommand())
- {
- cmd.CommandText = "Insert into T_Persons(Name,Age) values(@Name,@Age)";
- cmd.Parameters.Add(new SqlParameter("Name",name));
- cmd.Parameters.Add(new SqlParameter("Age",age));
- cmd.ExecuteNonQuery();
- }
- }
- }
- }
- }
- MessageBox.Show("导入成功!");
- }
- }
- }
- }