黑马程序员技术交流社区

标题: ADO.net中的小问题求指教 [打印本页]

作者: 王新阳    时间: 2012-11-19 20:07
标题: ADO.net中的小问题求指教
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?  不使用会怎样?
作者: 韩俊    时间: 2012-11-19 21:44

using在这里的作用是定义一个范围,在范围结束时处理对象。
例如当在某个代码段中使用了类的实例,而希望无论因为什么原因,只要离开了这个代码段就自动调用这个类实例的Dispose,用using就比较方便,也可以用try...catch来捕捉异常。如下代码:

using (Class1 cls1 = new Class1())
{
  // the code using cls1

} // call the Dispose on cls1 

当执行到using语句末端或中途引发异常则自动执行Dispose
作者: 韩俊    时间: 2012-11-19 21:44

using在这里的作用是定义一个范围,在范围结束时处理对象。
例如当在某个代码段中使用了类的实例,而希望无论因为什么原因,只要离开了这个代码段就自动调用这个类实例的Dispose,用using就比较方便,也可以用try...catch来捕捉异常。如下代码:

using (Class1 cls1 = new Class1())
{
  // the code using cls1

} // call the Dispose on cls1 

当执行到using语句末端或中途引发异常则自动执行Dispose




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2