从数据库中导入导出文件

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();
}


}
}
}
}

}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值