Tải bản đầy đủ (.pdf) (10 trang)

Tài liệu Create a Dialog Box to Connect to a New Database, Including Listing Available SQL Servers and Databases pdf

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (29.14 KB, 10 trang )

7.1 Create a Dialog Box to Connect to a New Database, Including Listing
Available SQL Servers and Databases
Users sometimes need to connect to various databases. An example of this is a large
company that might keep its site information in separate databases in the same-or even
different-SQL Servers. Management might need to point the application to different site
databases, depending on which one it needs to work with. This How-To shows you how
to create a dialog box to let the user pick the SQL Server and database and then create a
new connection based on the selections.
Within a database application, it is necessary to allow users to select a SQL Server back
end to which to connect. If you have created my application with the necessary
flexibility, you should not have hard-coded SQL Server or database names within my
application. How do you create a dialog box that lists available SQL Servers and
databases and that the user can utilize to connect to a new database?
Technique
For this How-To, you will be using the base object in SQL-DMO, which is the
Application object, and then the SQLServer object. You can use many objects off this
object, the first layer of which is shown in Figure 7.5.
Figure 7.5. These are just the tip of the iceberg as far as collections and objects used
in SQL-DMO.

Table 7.1 presents the objects, properties, and methods that will be used for this -To.
Table 7.1. SQL-DMO Objects Used for Listing SQL Servers, Databases, and
Connecting to a Database
Object Property/Method Description
Application NameList Collection used to hold the list of available
servers
ListAllAvailableServers Method used to retrieve available servers on the
network
SQLServer Connect Connection string that connects you to the SQL
Server, allowing you access to the databases
LoginSecure Flag that specifies that you want to connect to


the SQL Server using a trusted connection
Databases Collection of databases for the specified SQL
Server
You will also be using the OleDbConnection object.
Steps
Open and run the VB.NET -Chapter 7 solution. From the main Windows form, click on
the command button with the caption How-To 7.1.
When the form loads, you will see the SQL Servers that are available on your network. If
you are not on the network, you will only see a SQL Server called "local."
If you click on a SQL Server and you are in fact using the Windows NT Integrated
Security, then you will see the list of databases located in the chosen SQL Server.
You can then select a database and then click the Connection button. If you are
successful, you will see the connection string displayed in the text box at the bottom of
the form. The form will then look like the form displayed in Figure 7.6.
1. Create a Windows Form. Then place the controls shown in Figure 7.6 with the
following properties set.
Table 7.2. Label, ComboBox, ListBox, and Command Button Control
Property Settings
Object Property Setting
Label Name Label1
Text SQL Servers
ListBox Name lstSQLServers
Label Name Label2
Text Databases
ListBox Name lstDatabases
Label Name Label3
Text Connection String
TextBox Name txtConnectionString
Text Not Connected
Command Button Name btnConnect

Text Connect
2. As with some of the other chapters' projects, before creating the code that will be
attached to the Load event of the form, you need to create a support routine to
create the Connection string. Called BuildCnnStr, the function can be seen in
Listing 7.1. This function takes a server and database names passed to it and
returns a connection string. You will want to create a basic module in which to
keep the routine.
Listing 7.1 modSQLDMORoutines.vb: Creating a Connection String
Function BuildCnnStr(ByVal strServer As String, _
ByVal strDatabase As String) As String

Dim strTemp As String
strTemp = "Provider=SQLOleDB; Data Source=" & strServer & ";"
strTemp &= "Initial Catalog=" & strDatabase & ";"
strTemp &= "Integrated Security=SSPI"

Return strTemp
End Function
Although you could create a routine that would pass back a Connection object, a
more versatile method would be to pass back a string. The reason for this is that
some objects ask for a Connection object, but others just want a string.
3. On the form, add the code in Listing 7.2 to the Load event.
Listing 7.2 frmHowTo7_1.vb: Loading SQL Servers into a List Box
Private Sub frmHowTo7_1_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load

' Load up the SQL Servers
LoadSQLServers(Me.lstSQLServers)

End Sub

4. In the same module as step 2, create the routine called LoadSQLServers. After
establishing an instance of the SQL-DMO application, the code calls the
ListAvailableSQLServer method. If no names are loaded into the oNames
namelist object (meaning that they were not available or you weren't on the
network), then the (local) server is added to the list box. Otherwise, the list
returned is added to the list box. The first item in the list box is then selected,
causing the event described in the next step to be executed.
Listing 7.3 modSQLDMORoutines.vb: Loading SQL Servers into a List Box
Sub LoadSQLServers(ByRef lstSQLServers As ListBox)

Dim intCurrSQL As Integer
Dim oNames As SQLDMO.NameList
Dim oSQLApp As New SQLDMO.Application()

' Load available SQL Servers into a NameList
' (those that are able to be seen by the network)
oNames = oSQLApp.ListAvailableSQLServers

' Load the local instance as first in the list, if not on the network.
If oNames.Count = 0 Then
lstSQLServers.Items.Add("(local)")
End If

' Load the namelist into the list box
For intCurrSQL = 1 To oNames.Count
lstSQLServers.Items.Add(oNames.Item(intCurrSQL))
Next intCurrSQL

' Choose the first instance
lstSQLServers.SelectedIndex = 0

End Sub
Note

At this point, if you try to run your sample application, you might
get an error that includes the text QueryInterface for interface
SQLDMO.NameList failed. on the ListAvailableSQLServer
method. If this is the case, then you need to install Service Release
2 for SQL Server 2000. This will take care of this problem.
5. Add the code listed in Listing 7.4 to the SelectedIndexChanged event of the list
box called lstSQLServers. This routine starts by testing to see whether a SQL
Server and database have been selected. If so, the routine enables the btnConnect
button; otherwise, the button is disabled. The routine called GetSQLDatabases is
then called, passing selected SQL Server and the lstDatabases list box. You can
see the GetSQLDatabases routine listed in the next step.
Listing 7.4 frmHowTo7_1.vb: Enabling or Disabling the btnConnect Button
and Calling the Routine to Load the Database List Box
Private Sub lstSQLServers_SelectedIndexChanged(ByVal sender As
System.Object,
ByVal e As System.EventArgs) _
Handles lstSQLServers.SelectedIndexChanged

' If both the SQL Server and database are chosen, enable
' the Connect button.
If lstSQLServers.SelectedItems.Count > 0 And _
lstDatabases.SelectedItems.Count > 0 Then
Me.btnConnect.Enabled = True
Else
Me.btnConnect.Enabled = False
End If


GetSQLDatabases(Me.lstSQLServers.SelectedItem, Me.lstDatabases)

End Sub
6. Create the GetSQLDatabases routine by entering the code in Listing 7.5 to the new
module that you created in step 2. The first task that this routine attempts is to
connect to the server that is selected. If the routine can't connect, then the function
is exited; otherwise, the names of the database that are within the SQL Server are
loaded into the list box called lstDatabases.
Listing 7.5 modSQLDMORoutines.vb: Retrieving Database Names for a
Given SQL Server
Function GetSQLDatabases(ByVal strSQLServer As String, _
ByRef lstTemp As ListBox)

Dim intDBs As Integer
Dim db As Object
Dim strDBs As String

' Establish a connection to the server. If not, then exit the function.
Dim osvr As SQLDMO.SQLServer
osvr = New SQLDMO.SQLServer()

osvr.LoginSecure = True

Try

osvr.Connect(strSQLServer)

Catch excp As Exception

MessageBox.Show("There is a problem retrieving " & _

"databases for this server. " &
"Please check the name and try again. ", vbInformation,
"Error with Server")
Exit Function

End Try

' Clear the current list
lstTemp.Items.Clear()

' Load up the database names for the selected server into the list box.
For Each db In osvr.Databases
lstTemp.Items.Add(db.Name)
Next

End Function
7. Add the code from Listing 7.6 to the SelectedIndexChanged event of the
lstDatabases list box. This code is similar to the listing in step 4 in that it enables
the btnConnect button if an item is selected in both the lstSQLServers and
lstDatabases list boxes.
Listing 7.6 frmHowTo7_1.vb: Repopulating the List Boxes Based on the
Current Category Selected
Private Sub lstDatabases_SelectedIndexChanged(ByVal sender As System.Object,
_
ByVal e As System.EventArgs) _
Handles lstDatabases.SelectedIndexChanged

' If both the SQL Server and database are chosen,
' enable the Connect button.
If lstSQLServers.SelectedItems.Count > 0 And _

lstDatabases.SelectedItems.Count > 0 Then
Me.btnConnect.Enabled = True
Else
Me.btnConnect.Enabled = False
End If

End Sub
8. Add the code in Listing 7.7 to the Click event of the btnConnect button. In this
routine, a Connection object is instantiated and its Connection string is set to the
chosen SQL Server and database. If the connection has a problem opening, then
the Text property of txtConnectionString is set to an error message. Otherwise, the
Text property is set to the new connection string.
Listing 7.7 frmHowTo7_1.vb: Calling the Routine to Reload the lstUnSelected
List Box If This Check Box Is Changed
Private Sub btnConnect_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnConnect.Click

Dim ocnn As New OleDb.OleDbConnection()

Try
' Create the connection string and open the connection
ocnn.ConnectionString = BuildCnnStr(Me.lstSQLServers.SelectedItem, _
Me.lstDatabases.SelectedItem)
ocnn.Open()

Catch excp As Exception

Me.txtConnectString.Text = "Error with Connection"
Exit Sub


End Try

Me.txtConnectString.Text = ocnn.ConnectionString

End Sub
Figure 7.6. This form works great for logging users into a database using Windows
NT Integrated Security.

How It Works
When the form opens, the SQL Servers that are available on the network are loaded into
the first list box on the form. When the user clicks on a specific SQL Server, then the
databases from that SQL Server are loaded into the Databases list box. The user can then
select a database from the list. When the user does this, the Connect button is enabled. If
the user then clicks on the Connect button, the connect string is loaded into the text box
on the bottom of the form.
Comments
Like the others, this How-To is set up to use the Windows NT Integrated Security. If you
wanted to use the SQL Server security, you could add text boxes for login name and
password and then supply them when calling certain methods such as the Connect
method in the code listed in step 6. You would also then set the LoginSecure property
used in the same listing to False.
This How-To is great for exactly what it does: letting the user (or administrator) pick a
new SQL Server and database to connect to if necessary. You can then save this
connection string to a Public variable and use it with all your connection objects. You
will also be using similar controls and code for the rest of the How-Tos in this chapter.

×