黑马程序员_SQL Server数据的导入小结(1)

来源:互联网 发布:开源商城cms 编辑:程序博客网 时间:2024/04/30 14:16

----------------------Windows Phone 7手机开发、.Net培训、期待与您交流!----------------------这些知识点小结是根据杨老师的讲课做了整理,如有不清楚的请看杨中科老师的视频教程:【传智播客.Net培训—ADO.Net】10案例数据导入导出SQL Server中的数据导入导出


现在想把下列文本文件中的数据添加到数据库中:

Tom|23

Jack|28

Bob|36

创建好窗体项目后—>右击窗体项目—>添加—>新建项—>选择左边的“数据”—>再选择“基于服务的数据库”—>创建数据库—>创建表T_Persons用SQL语句创建表如:

 create table T_Persons(Id int not null,Name nvarchar(50) null,Age int null) --把Id定义为主键接下来就是代码:

using System;using System.Collections.Generic;

using System.ComponentModel;using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;using System.Windows

.Forms;using System.IO;

using System.Data.SqlClient;

namespace 数据导入导出

{

 public partial class Form1 : Form 

public Form1()

 { InitializeComponent(); } 

private void button1_Click(object sender, EventArgs e) 

OpenFileDialog ofdImport = new OpenFileDialog(); if (ofdImport.ShowDialog() == DialogResult.OK) 

using (FileStream fileStream = File.OpenRead(ofdImport.FileName))

{

 using (StreamReader streamReader = new StreamReader(fileStream))

 {

 string line = null; 

while ((line = streamReader.ReadLine()) != null)

 { 

string[] str = line.Split('|'); 

string name = str[0];

 int age = Convert.ToInt32(str[1]);

 using (SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=F:\WinForm窗体练习\数据导入导出\DBImport_Out.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("成功导入!~"); 

}

 

}

 

}

 }

 }

}

----------------------Windows Phone 7手机开发、.Net培训、期待与您交流!----------------------