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