您的位置:首页 > 数据库

C#Winform向数据库中导入.txt或者.CSV文件的数据

2016-02-24 22:45 477 查看
protected void ImportData(string filePath)
{
if (filePath.Length == 0)
{
MessageBox.Show("请选择要导入的txt文件");
}

using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
using (StreamReader sr = new StreamReader(fs))
{
//不读第一行的标题咧
sr.ReadLine();

string row_text = "";
string Exceptions = "";

List<string> sqlList = new List<string>();

while ((row_text = sr.ReadLine()) != null)
{
string[] datas = row_text.Split(',');
string sql = "insert into room (roomid,typeids,price,status,isdeleted ) values ('" + datas[0] + "'," + datas[1] + "," + datas[2] + "," + datas[3] + "," + datas[4] + ")";
sqlList.Add(sql);
}
try
{
DBUtil.ExSqlList(sqlList, out Exceptions);

MessageBox.Show("导入数据成功,共导入行数:" + sqlList.Count.ToString());
}
catch (Exception ex)
{
Exceptions = ex.Message.ToString();
MessageBox.Show("导入数据出错,错误信息:" + Exceptions);
}
}
}
}
下面给出向数据库中批量插入数据的DBUtil中的ExSqlList方法
public static bool ExSqlList(List<string > sqlList,out string exceptions)
{

exceptions = "";

bool isSuccess = true;

using (SqlConnection conn = new SqlConnection(sqlconn))
{
conn.Open();

SqlCommand cmd = new SqlCommand();

SqlTransaction trans = conn.BeginTransaction();

cmd.Connection = conn;

cmd.Transaction = trans;

try
{
foreach (string sql in sqlList)
{
cmd.CommandText = sql;

cmd.ExecuteNonQuery();
}

trans.Commit();
}
catch (Exception ex)
{
isSuccess = false;
trans.Rollback();
exceptions = ex.Message.ToString();
throw new ApplicationException(exceptions);
}
return isSuccess;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: