您的位置:首页 > 数据库

C# 将txt文件的数据库元组导入数据库,代码实现

2017-05-07 18:22 489 查看
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.IO;
namespace 导入数据
{
class Program
{
static void Main(string[] args)
{
string str = "Data Source=LENOVO-PC;Initial Catalog=MyDatabase;Integrated Security=True";
int n = -1;//判断是否导入成功
using (StreamReader sr=new StreamReader("1.txt"))
{
string line = sr.ReadLine();//第一行列名不要
using (SqlConnection sco = new SqlConnection(str))
{
string sql = "insert into users1(logName, logPassWord) values(@logName,@logPassWord)";
//用参数代替拼接,防止SQL注入漏洞
SqlParameter[] ps = {
new SqlParameter("@logName",System.Data.SqlDbType.VarChar),
new SqlParameter("@logPassWord",System.Data.SqlDbType.VarChar)
};
sco.Open();
using (SqlCommand scd = new SqlCommand(sql, sco))
{
scd.Parameters.AddRange(ps);
while ((line=sr.ReadLine())!=null)
{
string[] texts = line.Split(new char[] { ','},StringSplitOptions.RemoveEmptyEntries);
ps[0].Value = texts[0];
ps[1].Value = texts[1];
n = scd.ExecuteNonQuery();
}
}
sco.Close();
}
}
if (n > 0)
{
Console.WriteLine("导入成功!");
}
else
{
Console.WriteLine("导入失败!");
}
Console.ReadKey();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c# 数据