62,244
社区成员




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();
}
}
Create Table T_UserTable
(
RecID Int Identity(1,1) Not Null,
UserID Varchar(50) NULL,
Password Varchar(50) NULL,
Email Varchar(100) NULL
)