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

----------------------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培训、期待与您交流!----------------------

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值