using (FileStream filestream = File.OpenRead(OfdImport.FileName))
{
using (StreamReader streamReader = new StreamReader(filestream))
{
//连接数据库不能每次连接非常耗时,智能连接一次。
using ( SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated
Security=True;User Instance=True"))
{ //打开数据库
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "insert into T_person(Name,Age) values(@Name,@Age)";
string line = null;
while ((line=streamReader.ReadLine() )!= null)
{
string[] strs = line.Split('|');
string name = strs[0];
int age = Convert.ToInt32(strs[1]);
cmd.Parameters.Clear();//参数不能重复添加,在while中一直用一个SqlCommand对象
cmd.Parameters.Add(new SqlParameter("Name",name));
cmd.Parameters.Add(new SqlParameter("Age",age));
cmd.ExecuteNonQuery();
}
}
}
}
} |