Вы находитесь на странице: 1из 16

Capítulo 8

COM
Objetivo
• Crear una biblioteca de clases que
permita acceder a una base de datos.
Imports
• Imports System
• Imports System.Data
• Imports System.Data.SqlClient
• Imports System.Text
Declaración de variables
• Namespace SQLNameSpace
• Public Class SQLClass
• Private ls_sql as string
• Private ls_ConnStr as string
Constructor
Public Sub New()
MyBase.New()
ls_sql = ""
ls_ConnStr = ""
End Sub
Propiedades
Public Property SQL as string
Get
Return ls_sql
End Get
Set
ls_sql = value
End Set
End Property
Public Property ConnStr as string
Get
Return ls_ConnStr
End Get
Set
ls_ConnStr = value
End Set
End Property
Método Populate
Public Function Populate() As DataView
Dim myConnection As SqlConnection
Dim myCommand As SqlDataAdapter
Dim ds As New DataSet
myConnection = New SqlConnection(ConnStr)
myCommand = New SqlDataAdapter(SQL,
myConnection)
myCommand.Fill(ds, "vTable")
Populate = ds.Tables("vTable").DefaultView
End Function
Método RunSql….
Function RunSql(vsql as string) as String
Dim Message As String = ""
Dim errString As String = ""
try
Dim myConnection As SqlConnection
myConnection = New SqlConnection(ConnStr)
Dim mycommand As New SqlCommand(vsql,
myConnection)
myconnection.Open()
myCommand.ExecuteNonQuery()
myconnection.Close()
Método RunSql
Catch ex As SqlException
Dim errItem As SqlError
For Each errItem In ex.Errors
errString += ex.Message + " "
Next
Message = "SQL Error.Details follow:<br/><br/>" & errString
Catch myException as Exception
message = "Exception: " + myException.ToString()
End try
RunSql = message
End Function
End Class
End Namespace
Imports
Imports BC_Bhasin_Capitulo_08.SQLNameSpace
Partial Class TestVbClass
Inherits System.Web.UI.Page
Dim Comp As SQLClass
Dim ConnStr As String
Dim SQL As String
Load
Sub Page_Load(ByVal Source As Object, ByVal E
As EventArgs)
Comp = New SQLClass()
Comp.ConnStr = "Data Source=(local);Initial
Catalog=ASPNET;Integrated Security=True;"
If Not (IsPostBack) Then
ReBind()
End If
End Sub
Insert
Sub Insert_click(ByVal Sender As Object, ByVal E
As EventArgs)
SQL = "Insert into
Masters(code_display,code_category,type)"
SQL = SQL + "Values ('test',701,'E')"
Comp.RunSql(SQL)
ReBind()
Message.Text = "Inserted test record... "
End Sub
Delete
Sub Delete_click(ByVal Sender As Object, ByVal E
As EventArgs)
SQL = “delete from masters where
code_display = ‘test‘ “
Comp.RunSql(SQL)
ReBind()
Message.Text = “Deleted all test records...”
End Sub
Update
Sub Update_Click(ByVal Sender As Object, ByVal
E As EventArgs)
SQL = "UPDATE Masters Set Opening = 90
WHERE code_display = 'test'"
Comp.RunSQL(SQL)
ReBind()
Message.Text = "Updated all test records:
Set closing balance = 90...! "
End Sub
rebind
Sub ReBind()
Comp.SQL = "select * from Masters"
DataGrid1.DataSource =
Comp.populate()
DataGrid1.DataBind()
End Sub

Вам также может понравиться