private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog afd = new OpenFileDialog();
if (afd.ShowDialog()!=System.Windows.Forms.DialogResult.OK)
{
return;
}
string fileName = afd.FileName;
if (Path.GetExtension(fileName)!=".csv")
{
MessageBox.Show("文件名后缀必须是.csv");
return;
}
DataTable table = new DataTable();
using(Stream stream=new FileStream(fileName,FileMode.Open,FileAccess.Read))
using(StreamReader sr=new StreamReader(stream,Encoding.Default))
{
string firstline = sr.ReadLine();
string line; #region 把创建的列加入表的列集合中
//Id
DataColumn column = new DataColumn();
column.ColumnName = "Id";
column.DataType = System.Type.GetType("System.Int32");
table.Columns.Add(column);
//MobileNumber
column = new DataColumn();
column.ColumnName = "MobileNumber";
column.DataType = System.Type.GetType("System.String");
column.MaxLength = ;
table.Columns.Add(column);
//MobileArea
column = new DataColumn();
column.ColumnName = "MobileArea";
column.DataType = System.Type.GetType("System.String");
column.MaxLength = ;
table.Columns.Add(column);
//MobileType
column = new DataColumn();
column.ColumnName = "MobileType";
column.DataType = System.Type.GetType("System.String");
column.MaxLength = ;
table.Columns.Add(column);
//AreaCode
column = new DataColumn();
column.ColumnName = "AreaCode";
column.DataType = System.Type.GetType("System.String");
column.MaxLength = ;
table.Columns.Add(column);
//PostCode
column = new DataColumn();
column.ColumnName = "PostCode";
column.DataType = System.Type.GetType("System.String");
column.MaxLength = ;
table.Columns.Add(column);
#endregion while ((line = sr.ReadLine())!=null)
{
string[] mobileMsg = line.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
int Id = Convert.ToInt32(mobileMsg[]);
string MobileNumber = mobileMsg[].Trim('"');
string MobileArea = mobileMsg[].Trim('"');
string MobileType = mobileMsg[].Trim('"');
string AreaCode = mobileMsg[].Trim('"');
string PostCode = mobileMsg[].Trim('"');
//创建行,把行加入表的行集合中
DataRow row = table.NewRow();
row["Id"] = Id;
row["MobileNumber"] = MobileNumber;
row["MobileArea"] = MobileArea;
row["MobileType"] = MobileType;
row["AreaCode"] = AreaCode;
row["PostCode"] = PostCode;
table.Rows.Add(row);
}
} int i = table.Rows.Count;
Stopwatch sw = new Stopwatch();
sw.Start();
using (OracleBulkCopy bulkCopy = new OracleBulkCopy(OracleHelper.CreateConnection()))
{
bulkCopy.DestinationTableName = "T_MOBILE";
foreach (DataColumn column in table.Columns)
{
bulkCopy.ColumnMappings.Add(column.ColumnName, column.ColumnName);//源列名->目标列名
}
try //如果发生异常就回滚
{
bulkCopy.WriteToServer(table);//把table表写入数据库表中
// tx.Commit();
}
catch (Exception ex)
{
// tx.Rollback();
throw new Exception(ex.Message);
}
}
sw.Stop();
MessageBox.Show("耗时:" + sw.ElapsedMilliseconds + "秒");
// }
}