private void button1_Click(object sender, EventArgs e)
{
if (ofdImport.ShowDialog() == DialogResult.OK)//显示对话框
{
using (FileStream fileStream = File.OpenRead(ofdImport.FileName)) //打开文件进行读取
{
using (StreamReader strReader = new StreamReader(fileStream))
{
string line = null;
while ((line = strReader.ReadLine()) != null)
{
string[] strs = line.Split('|');
string name = strs[0];
int age = Convert.ToInt32(strs[1]);
using (SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDBFilename=C:\Users\lenovo\documents\visual studio 2010\Projects\Sharp基础\ado数据导入导出\MyDB.mdf;integrated Security=True;User Instance=True"))
{
con.Open();
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "insert into T_Persons(Name,Age) values(@Name,@Age)";
cmd.Parameters.Add(new SqlParameter("Name", name));
cmd.Parameters.Add(new SqlParameter("Age", age));
cmd.ExecuteNonQuery();
}
}
}
}
}
MessageBox.Show("导入成功");
}
为什么要使用Using? 不使用会怎样? |