视频讲的是先建立文件的数据流再建立与数据库的连接,代码如下:
using (FileStream fileStream = File.OpenRead(ofdImport.FileName))
{
//StreamReader 类:实现一个 TextReader,使其以一种特定的编码从字节流中读取字符。
using (StreamReader streamReader = new StreamReader(fileStream))
{
string line = null;
//创建连接是非常耗时的,因此不要每次操作都创建连接,一般将它写在循环外
using (SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database2.mdf;Integrated Security=True;User Instance=True"))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "insert into T_User(FName,FAge) values(@Name,@Age)";
......
}
}
}
}
我觉得也可以先建立与数据库的连接再建立文件的数据流,像这样:
using (SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database2.mdf;Integrated Security=True;User Instance=True"))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "insert into T_User(FName,FAge) values(@Name,@Age)";
using (FileStream fileStream = File.OpenRead(ofdImport.FileName))
{
//StreamReader 类:实现一个 TextReader,使其以一种特定的编码从字节流中读取字符。
using (StreamReader streamReader = new StreamReader(fileStream))
{
string line = null;
......
}
}
}
}
初学,想咨询一下老鸟我的想法对吗? |