Net大文件读取,批量插入SQL性能分析
ps:刚才无事,想看看自己的账号是否在其中,顺便就练习了一下文件读写。正题:
FileStream和StreamReader是我们经常用来读取文件的两个类,读取数据的时候我们用ReadLine和ReadBlock两个方法,
这里用ReadLine读取,如果是本地读取文件的话ReadLine就可以了。
这里测试读写10万条数据并插入数据库,1000条为一批,共耗时37秒,感觉性能就这样,这里主要一点就是循环里不忘批量提交,减少数据库连接次数,如果用SqlBulkCopy类,减少提交次数,估计性能更佳。
各位如有好的方法和性能改进的地方,请分享一下,谢谢。
测试读取的文件样式见CSDN热点文件,>280M,文件格式如下:
abcdefg # 123456 # abc@live.cn
abd25fg # 123f45f6 # abfjc@live.cn
测试代码如下:
class Program
{
static void Main(string[] args)
{
ReadTxtToDatabase();
}
private static void ReadTxtToDatabase()
{
string FilePath = @"D:\net.sql";
string Sqlstr = string.Empty;
int j = 0;
DateTime StartTime = DateTime.Now;
if (File.Exists(FilePath))
{
FileStream fs = System.IO.File.Open(FilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read, FileShare.None);
StreamReader m_streamReader = new StreamReader(fs);
m_streamReader.BaseStream.Seek(0, SeekOrigin.Begin);
string strLine = m_streamReader.ReadLine();
int i = 1;
while (strLine != null)
{
int index = strLine.IndexOf(" # ");
string UserID = strLine.Substring(0, index).Trim();
strLine = strLine.Substring(index + 3, strLine.Length - (index + 3));
index = strLine.IndexOf(" # ");
string Password = strLine.Substring(0, index).Trim();
string Email = strLine.Substring(index + 3, strLine.Length - (index + 3)).Trim(); ;
strLine = m_streamReader.ReadLine();
//Console.WriteLine("UserID:" + UserID + " Password:" + Password + " Email:" + Email);
UserID = UserID.Replace("'", "''");
Password = Password.Replace("'", "''");
Email = Email.Replace("'", "''");
Sqlstr += " Insert Into T_UserTable(UserID,Password,Email) Values('" + UserID + "','" + Password + "','" + Email + "')";
if (i == 1000) //1000条一插,减少连接次数
{
Insert(Sqlstr);
Sqlstr = string.Empty;
i = 0;
Console.WriteLine("插入第" + j + "批完毕!");
j++;
if (j == 100) //测试100批数据
{
goto lableA;
}
}
i++;
}
m_streamReader.Close();
}
Insert(Sqlstr);
lableA:
TimeSpan tss = DateTime.Now - StartTime;
int times = tss.Seconds;
Console.WriteLine("耗时:" + times + "秒");
Console.WriteLine("全部插入完毕!");
Console.WriteLine("共" + j + "批!");
Console.ReadLine();
}
private static void Insert(string sql)
{
string connStr = @"Data Source=MSSQL2008;Database=Test;uid=Tuser;pwd=Tuser_123;";
SqlConnection conn = new SqlConnection(connStr);
SqlCommand comm = new SqlCommand(sql, conn);
conn.Open();
comm.ExecuteNonQuery();
conn.Close();
conn.Dispose();
}
}
数据库表结构
--------------------编程问答-------------------- Plinq+异步I/O --------------------编程问答-------------------- 用MSSQL导入工具导入数据库,然后做查询不就行了,而且想怎么查就怎么查 --------------------编程问答--------------------
Create Table T_UserTable
(
RecID Int Identity(1,1) Not Null,
UserID Varchar(50) NULL,
Password Varchar(50) NULL,
Email Varchar(100) NULL
)
试试 --------------------编程问答-------------------- 用异步,可以值得一试 --------------------编程问答-------------------- --------------------编程问答-------------------- --------------------编程问答-------------------- 1000条数据提交一次,看来LZ没有玩过大数据量的东西
用SqlBulkCopy把, 10w条提交一次,如果你的机器不是古董机器,应该在2秒以内
补充:.NET技术 , ASP.NET