---
title: "从数据库中导入导出文件"
author: "mywebcode"
date: "2012-11-30T16:13:00Z"
tags: []
slug: "untitled"
draft: false
lastmod: "2013-05-08T10:26:24Z"
id: 1862857
url: "https://mywebcode.iteye.com/blog/1862857"
---

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Web;  
using System.Web.UI;  
using System.Web.UI.WebControls;  
using System.Data.SqlClient;  
using System.IO;

namespace 文件的导入导出  
{  
public partial class 数据导入导出到文本文件 : System.Web.UI.Page  
{  
protected void Page\_Load(object sender, EventArgs e)  
{

}  
//导入到文本文件中  
protected void Button1\_Click(object sender, EventArgs e)  
{  
string constr = "data source=.;initial catalog=TestSchool;user id=sa;password=7777777";  
using (SqlConnection conn = new SqlConnection(constr))  
{  
string sql = "select * from denglujicuo";  
using (SqlCommand cmd = new SqlCommand(sql, conn))  
{  
conn.Open();  
using (SqlDataReader reader = cmd.ExecuteReader())  
{  
if (reader.HasRows)  
{  
using (StreamWriter sw = new StreamWriter(@"H:\\denglujicuo.txt"))  
{

while (reader.Read())  
{  
object username = reader.GetValue(0);  
object password = reader.GetValue(1);  
string line = string.Format("{0}-{1}", username, password);  
sw.WriteLine(line);  
}  
conn.Close();  
}  
}  
}  
}

}  
}  
//将文本文件导出到数据库里  
protected void Button2\_Click(object sender, EventArgs e)  
{  
using (StreamReader sr = new StreamReader(@"H:\\denglujicuo.txt"))  
{  
string constr = "data source=.;initial catalog=TestSchool;user id=sa;password=7777777";  
using (SqlConnection conn = new SqlConnection(constr))  
{  
conn.Open();  
string sql = "insert into denglujicuo(username,password) values(@username,@password)";  
using (SqlCommand cmd = new SqlCommand(sql, conn))  
{  
//创建个数组接受文本文件中传过来的值

SqlParameter p1 = new SqlParameter("@username", System.Data.SqlDbType.VarChar);//没读到文本之前  
SqlParameter p2 = new SqlParameter("@password", System.Data.SqlDbType.VarChar);  
cmd.Parameters.Add(p1);  
cmd.Parameters.Add(p2);

while (!sr.EndOfStream)//当sr没有读到最后时就继续  
{  
string line = sr.ReadLine();  
string\[] r = line.Split('-');

p1.Value = r\[0];  
p2.Value = r\[1];  
cmd.ExecuteNonQuery();  
}

}  
}  
}  
}

}  
}