MESSAGE #18854 (อ่าน 158 ครั้ง) Using .... End Using ใช้ยังไงครับ Using .... End Using ใช้ยังไงครับ กับ Try ... Catch ... End Try
ใช้ต่างกันยังไงครับ
ขอขคุณครับ ปอ
-----------------------
Using จะทำการ Dispose ตัวแปร command ให้อัตโนมัติครับ
ส่วน Try .. Catch ใช้ดักเมื่อเกิด throw exception
tony
----------------------
Using sample
Using conn As New SqlConnection(dsn) Using cmd As New SqlCommand("SELECT * FROM Employees", conn) conn.Open() Using rdr As SqlDataReader = cmd.ExecuteReader() While rdr.Read() Console.WriteLine(rdr(0)) End While End Using End Using End Using Nine (นาย) -------------------- ต้วอย่าง แบบไม่ใช้ Using Dim x2 As New Employee("x2") x2.Name = "test"
If (TypeOf x2 Is IDisposable) Then DirectCast(x2, IDisposable).Dispose() End If แบบใช้ Using Using x3 As New Employee("x3") x3.Name = "test" End Using
Iwis -------------------------------
Using cn1 As New SqlConnection(My.Settings.NorthwindConnectionString), _ cmd1 As New SqlCommand(sql1, cn1) cn1.Open() Dim reader As DataReader = cmd1.ExecuteReader() Do While (reader.Read()) Dim sql2 As String sql2 = "...." Using cn2 As New SqlConnection(My.Settings.NorthwindConnectionString), _ cmd2 As New SqlCommand(sql2, cn2) cn2.Open() cmd2.ExecuteNonQuery() End Using Loop reader.Close End Using surrealist ---------------------- Using da As New SqlDataAdapter(sql, cn) Dim cmd As SqlCommand = da.SelectCommand cmd.Parameters.Add("@para1", SqlDbType.XYZ).Value = yourValue ' ---- เมื่อเราสั่ง Fill, DataAdapter จะเอา SelectCommand ของมันไป ExecuteReader ' ---- เพื่อนำข้อมูลที่ได้จาก DataReader มา "Fill" ใส่ DataSet/DataTable ที่เรากำหนด da.Fill(ds, "Table1") End Using ' ... Return(ds)
surrealist
ขอบคุณทุกๆท่านที่มีรายชื่อครับ ที่มา ณ www.greatfriends.biz
ไม่มีความคิดเห็น:
แสดงความคิดเห็น