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

Public Class DatabaseConnector

''' <summary>
''' Returns an OLEDB connection string to an Access 2010 database
''' </summary>
''' <returns>The OLEDB connection string to the Access 2010 database</returns>
Private Function GetConnectionString() As String

' Create the Connection string


Dim strConnection As String
strConnection = _
"Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=C:\Test\DatabaseFile.accdb;" & _
"User ID=Admin;Password=;"

' Return the Conntection string


GetConnectionString = strConnection

End Function ' End of: Private Function GetConnectionString() As String

''' <summary>
''' Allow the user to execute non-record returning queries
''' </summary>
''' <param name="SqlCode">The SQL Statement to execute against the
database</param>
''' <returns>True if successful, otherwise False</returns>
Public Function RunSqlNonQuery(SqlCode As String) As Boolean
On Error GoTo HandleErrors

Dim bResult As Boolean


Dim cmd As OleDb.OleDbCommand

' Create the OLEDB Command object


cmd = New OleDb.OleDbCommand(SqlCode)

' Open the Connection


cmd.Connection = New OleDb.OleDbConnection(GetConnectionString())
cmd.Connection.Open()

' Execute the SQL Statement


cmd.ExecuteNonQuery()

' It looks like we've succeeded - return True


bResult = True

ExitFunction:

' Close the connection


If (Not IsNothing(cmd.Connection)) Then
If (cmd.Connection.State <> ConnectionState.Closed) Then
cmd.Connection.Close()
End If
End If

' Return the result and exit


RunSqlNonQuery = bResult
Exit Function
HandleErrors:

' Handle any errors here...


MsgBox("An error was raised!" & vbNewLine & "Message: " & Err.Description,
MsgBoxStyle.Critical, "Error")
Err.Clear()
bResult = False ' Return failure
Resume ExitFunction

End Function ' End of: Public Function RunSqlNonQuery(SqlCode As String) As


Boolean

End Class ' End of: Public Class DatabaseConnector

Dim dbConnector As New DatabaseConnector


Dim strSql As String

' Create an INSERT SQL Statement


strSql = _
"INSERT INTO [Table1] ( [Field1], [Field2] ) " & _
"VALUES (""Field 1 Value"", ""Field 2 Value""); "

' Execute the SQL Statement against the Access database


dbConnector.RunSqlNonQuery(strSql)