Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 115 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
115
Dung lượng
1,58 MB
Nội dung
able to retrieve the data it houses. In many cases, with the proper network security, a user could open, copy, or even delete the database. There are also several options for working with security. Many developers may want to use a combina- tion of the User-Level Security Wizard and code. The wizard is excellent for establishing users and groups for user-level security. However, many developers may want to use code to make changes after the initial permissions have been set. And it’s certainly handy to use code to generate custom documen- tation about user-level security. Either way, you are sure to find that Access provides powerful solutions for developing secure applications. The Access help files, knowledge base articles, and MSDN all provide useful instructions and guidance about various aspects of Access security and how to secure data and code. Chapter 22 covers more infor- mation about macro security how Access enhances protection for machines from malicious database attacks that use code in database files. 648 Chapter 18: Database Security 47033c18.qxd:WroxProgRef 3/30/07 12:28 AM Page 648 Understanding Client-Server Development with VBA Access makes it easy to create applications that interact with other database formats and enter- prise-level database servers. Unfortunately, the easiest methods are not always the best, and incor- rect choices can have serious long-term effects on the design, stability, maintenance, and overall success of a project. A thorough understanding of how Access interacts with other databases and the various alternatives available for developers is critical to making the best design decisions for any given application. In a typical business environment, Access database applications tend to sprout up because some individual or small group needs functionality and creates an Access database to implement a viable solution. Other people or groups notice the application’s usefulness and decide to use the solution as well. Someone may even split the data tables into a backend database and link the tables in the front-end application so that large numbers of users can use a local copy on their machines and connect to the tables stored on a central server. Before long, what began as a per- sonal database application is now shared on the network server, contains hundreds of megabytes of business data, is used on a daily basis by 50 or so people, and requires 2 or 3 people just to maintain and administrate the database. The application has become an unintended, albeit critical, piece of the company’s business process. The solution is cost effective. So another database is created for a different problem, and then a third database, and so on until there are hundreds of applications all over the network, some in use, some dead, and maybe some that were never even completed. Many IT workers cringe at a mere whisper of the words “Access database” because these applications become difficult and expensive to track, maintain, and support. Where does all this data come from? Who has access to the data? Who backs up the data? Who developed this application? Who is maintaining and sup- porting this database? These are just some of the questions to ask when thinking about how to deal with large numbers of Access databases in a business environment. 47033c19.qxd:WroxProgRef 3/30/07 12:28 AM Page 649 Fortunately, there are some easy answers to these tough questions that allow users the flexibility of creat- ing Access applications and save IT the headache of having to support and maintain all of the data. If the data is stored in a controlled, centralized location, an IT department can effectively manage the database and control which users can view/modify the data. A more ideal solution would be using a database server as the centralized location, enabling both developers and administrators to leverage the server’s features to help them with their tasks. Fortunately, Access provides the capability to create front-end applications to connect to separate, back-end data sources of many different types. Being able to connect to remote data sources is the basis of the database application architecture often referred to as a client-server application, which we will discuss in the next section. Client-Server Applications An Access application with only local tables is a file-server application, where all processing occurs on the local client machine regardless of where the file is physically stored. The idea is that the local machine’s or network server’s file system will accept commands from the Access Connectivity Engine — ACE database engine — that are made from Access on the local machine during use of the application. This is the key difference between a file-server and a client-server application. In the client-server application model, an application residing on the local machine retrieves data from a data source that is completely separate from the client application. Often there are many copies of the client application retrieving data from a single or a few remote data sources, which are typically stored in a network location, so that the data can be shared among all clients. At a minimum, the term client- server implies the design of the application is separated into at least two components: a client-side appli- cation that allows the user to interact with the data stored in the database, and a server that is responsible for maintaining data and executing requests from the client application. This architectural difference in an application can yield great performance and maintenance benefits, especially when large numbers of users are frequently interacting with the data. Although it’s tempting to think that simply moving the application’s tables to a Microsoft SQL Server 2005 database server will make the program a client-server application, in reality, that’s only the begin- ning. It is more accurate to say: moving the data to SQL Server provides the potential for a client-server application. The application still needs to take advantage of that potential for all of the benefits to be realized. Depending on the application, making client-server applications may also yield a few draw- backs. For reasons discussed later in this chapter, it is not uncommon for an application to be slower immediately after migrating the data from the local file to a SQL Server (or other server) database. Regardless of the client format chosen, significant performance, security, maintenance, and storage benefits can be realized through careful planning of the design of the database solution. Using the Sample Files This chapter defines techniques for creating client-server applications that, in some cases, store data in a SQL Server database. These SQL Server-specific examples use Microsoft SQL Server Express Edition 2005 as the database server, installed on the local machine. If you do not have SQL Server Express 2005 installed, you can download it for free from Microsoft. SQL Server Express binaries and samples can be found at http://microsoft.com/sql/editions/express/default.mspx. In addition, the database used for the examples in this chapter is included with the download files for the book. Find the Sample.SQL script, which will build the SQL database when invoked in SQL Server. 650 Chapter 19: Understanding Client-Server Development with VBA 47033c19.qxd:WroxProgRef 3/30/07 12:28 AM Page 650 After you’ve installed SQL Server, you may want to make a few modifications to the server’s configura- tion. By default, network connections from the TCP/IP connections are disabled. 1. From the Windows Start menu, invoke the SQL Server Configuration Manager. The configura- tion manager will be invoked. In the left pane in the manager, select SQL Server 2005 Network Configuration ➪ Protocols for SQLEXPRESS. 2. Notice that TCP/IP connections are marked as disabled. This means that incoming connection requests from the network will be denied. To enable network connections, right-click the TCP/IP option on the right side of the screen and select Enabled. A message tells you that changes will take effect after the server is restarted. Click OK and you return to the configuration manager. In addition to enabling the TCP connections in SQL Server Express, the Windows Firewall set- ting may also need to be configured to accept incoming TCP connections. Consult Windows Firewall help if this is the case. 3. In the left pane, select the SQL Server 2005 Services option again and in the right pane, right- click SQL Server and choose Stop. This stops SQL Server. Right-click the SQL Server option again and choose Start to restart the server, applying the changes for network connections. Then exit the configuration manager program, as the SQL Server is now configured correctly. Installing the Sample Database Once the SQL Server has been installed and configured, the machine is ready to add the sample database to the system. 1. From the Windows Start menu, navigate to the Microsoft SQL Server 2005 folder and click on the SQL Server Management Studio Express option. If the SQL Server has been installed on a machine running Windows Vista, Management Studio Express may need to be run as an administrator before any changes can be made to the server. To run the application as an administrator, right-click the icon for Management Studio Express and choose Properties. The properties dialog box opens. On the Compatibility tab, check the Run as Administrator option and apply the setting. Now, every time the application is run from the icon, it will run in admin- istrator mode. SQL Server Express Edition 2005 If you do not have SQL Server installed, but want to use the sample files or try the examples in this chapter, Microsoft SQL Server Express Edition 2005 can be down- loaded and installed for free. Just navigate to http://microsoft.com/sql/edi- tions/express/default.mspx and follow the links. Be sure to download SQL Server Management Studio Express as well because it provides a visual interface for working with the SQL Server toolset. Installing SQL Server Express 2005 requires that the .NET Framework 2.0 or greater be installed on the machine prior to the server installation. You can download SQL Server 2005 Express Edition SP1, which is used in the examples, onto your Windows Vista machine. Follow the installation instructions provided on the websites. 651 Chapter 19: Understanding Client-Server Development with VBA 47033c19.qxd:WroxProgRef 3/30/07 12:28 AM Page 651 2. The Connect to Server dialog box will be invoked. By default, the name of the SQL Server is machine name\SQLEXPRESS. Input the Server Name and click the Connect button. Management Studio Express is connected and you are ready to create the sample database. 3. In Object Explorer, right-click the Databases folder and choose New Database. Type NorthwindCS for the Database name in the New Database dialog box and then click OK. A new empty database with the name NorthwindCS is created. Now you’re ready to import all of the objects and data in the Sample.SQL file included in this chapter’s download files. 4. From the File menu, choose Open and browse to Sample.SQL. This action prompts you to con- nect to SQL Server again, so click the Connect button again. 5. Sample.SQL will be open for viewing in the main document window of Management Studio. Click the Execute button on the SQL Editor’s toolbar to create the sample database. The script runs and the new database table schema, data, and other objects are created. The sample data- base is ready for use on the new SQL Server. Now you can get down to business. Choosing the Correct File Format Many misconceptions exist regarding the differences between the Access Project (ADP) file format and the various Access database (ACCDB and MDB) file formats. Even before ADP files were available (introduced in Access 2000), many developers did not fully understand how MDB files worked or how to optimize their usage in a client-server environment. Although even serious design mistakes can still provide acceptable performance when there is not a large amount of data in the database, as the data grows, the inefficient design becomes more and more detrimental to the application’s performance and reliability. Microsoft Office Access 2007 features a brand new database engine: the Access Connectivity Engine (ACE) — also called the Access database engine. If you’ve used previous versions of Access, you are probably very familiar with ACE’s predecessor, the Jet database engine. ACE is a privatized version of the Jet database engine with a number of feature enhancements. Using ACE, Access 2007 supports creat- ing the following file formats: ACCDB (Access 2007 file format), MDB (Access 2000 and 2002-2003 file formats), ADP (Access Data Project), MDE (Access Complied MDB database), ACCDE (Access Complied ACCDB database), MDA (Access MDB Add-in), ACCDA (Access ACCDB Add-in), and ACCDC (Access Signed CAB file). This section discusses some of the differences between the ACCDB/MDB and ADP file formats. What Are ACCDB and MDB Files? Since its inception in 1992, the Jet (Joint Engine Technology) database engine has been the backbone for every Access version until the Access 2007 release. One of the main reasons Jet has been so successful is that it has been available since Microsoft Windows 3.0. Originally released as a part of Access, it was eventually separated and shipped with Microsoft Windows as a system component. This meant that any ODBC or compatible development environment could employ the Jet database engine without requiring that Access be installed on the system. For example, a Microsoft Visual Basic application could make use of a Jet MDB file format database without requiring Access be installed — and many did! As mentioned earlier, one of the highlights of the Access 2007 release is the introduction of ACE, the Access database engine. Fortunately, ACE supports all of the features that Jet provided in the 2000 and 652 Chapter 19: Understanding Client-Server Development with VBA 47033c19.qxd:WroxProgRef 3/30/07 12:28 AM Page 652 2002-2003 MDB file formats. While data in certain legacy formats can still be edited via Access 2007, it should be noted that 2000 and 2002-2003 MDB files are the only two legacy MDB file formats still fully supported for database design by Access 2007. To support much of the new feature work, such as Complex Data or Attachment fields, Microsoft has introduced a new Access 2007 file format called ACCDB. While ACCDB is essentially the MDB file format plus a few more system tables, there are some key differences. The following is a list of features that the ACCDB file format supports, but are unsup- ported for MDB files: ❑ Complex Data and Attachment fields for tables ❑ Complex Data fields for linked tables to SharePoint lists ❑ Append-Only Memo fields ❑ Database file encryption ❑ The Access 2007 Import/Export specifications Additionally, there are several features supported in MDB, but not in ACCDB, including: ❑ User-level security and the Workgroup Database (MDW) files ❑ Database file encoding ❑ Digital Signatures (2003 MDB file format only) On the other hand, MDB and ACCDB file format databases are similar in that they store all of the data, database objects, VBA modules, and database properties directly in a single file structure. Starting with Access 2000, all non-data objects are stored in a single record of a database system table used by Access. Upon opening a database file, Access searches for this record and loads the VBA project and all other objects employed by the database application. In addition to storing the table data directly within the file, the MDB and ACCDB file formats support linking tables to external data sources such as ODBC, SQL server tables, SharePoint lists, other MDB/ACCDB files, Excel Workbook files, and so on. The Microsoft Office Access Object Model, DAO, and ADO components all support working with linked tables to develop robust application feature sets for database applications. However, simply creating an MDB with linked tables to a SQL Server table does not make it an ADP file, as you will see shortly. First, let’s explore a little more about linked tables and MDB and ACCDB files. Linking to External Data Access 2007 supports connecting to a wide variety of different types of data sources; although some are read-only, many are fully updatable from an Access application. This is because different data source types use separate, but distinct methods to connect to the data. Indexed Sequential Access Method (ISAM) drivers are generally used for connecting to other desktop or file-based data sources, such as Excel, text, and HTML. On the other hand, Open Database Connectivity (ODBC) data source vendors typically supply connection utilities for use with their specific database products. In most cases, the client machine needs to have a specific database product’s relevant utilities installed before an applica- tion can connect to the data source. For example, even though Access ships with an ODBC driver for Oracle, the Oracle client utilities still need to be installed on the machine for the ODBC driver to be of any use to an Access application. 653 Chapter 19: Understanding Client-Server Development with VBA 47033c19.qxd:WroxProgRef 3/30/07 12:28 AM Page 653 Fortunately, Access makes linking many different data sources extremely easy. The following steps out- line a common method for creating a connection to a SQL Server Express database: 1. To create a link to an external data source from an Access ACCDB file, select External Data tab on the Ribbon. In the Import section, click the More button on the Ribbon and choose the ODBC database option. This opens the Get External Data Wizard, as shown in Figure 19-1. Figure 19-1 2. In the wizard, choose Link To The Data Source By Creating A Linked Table (the second radio button in the list) and then click OK. This invokes a Select Data Source dialog box that looks similar to the one shown in Figure 19-2. The Select Data Source dialog box enables you to create links from the current database to other supported ODBC databases. Figure 19-2 654 Chapter 19: Understanding Client-Server Development with VBA 47033c19.qxd:WroxProgRef 3/30/07 12:28 AM Page 654 3. You can select a pre-existing data source name (DSN) connection or create a new data source. For now, open the Machine Data Source tab and click the New button. The Create New Data Source dialog box opens (see Figure 19-3). On Windows Vista, you may get a warning that you are not able to create system DSN connections because of how Access is run and/or the permission level of the Windows account. The warning should provide instructions so that you can create a user DSN. Figure 19-3 The path contained here determines the location in the Registry where the connection informa- tion will be stored. User-specific data source locations are stored to the following registry key and are available only to the current user: HKEY_CURRENT_USER\Software\ODBC\ODBC.INI Machine data sources are available for all user profiles and are stored to the following registry location: HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBC.INI Odd but true: HKCU has a proper case Software node, while HKLM has an uppercase SOFTWARE node. The registry is case insensitive, so it would be okay to make these consistent, although you will see the different cases when you open the registry editor UI. 4. To create a system DSN connection on Windows Vista, you must be logged into an Administrator account or Access will need to be run as an administrator. For now, choose User Data Source, and click the Next button. The next Create New Data Source page opens, as shown in Figure 19-4. 5. At this point, the screens and options presented vary depending on what drivers are present on the machine and which drivers you choose. For now, select SQL Native Client option from the list, click Next, and then click Finish to bring up the dialog box information specific to SQL Server, as shown in Figure 19-5. 655 Chapter 19: Understanding Client-Server Development with VBA 47033c19.qxd:WroxProgRef 3/30/07 12:28 AM Page 655 Figure 19-4 Figure 19-5 6. Enter TestDSN for a name and, optionally, the description for the connection. You can type in the name of your SQL Server or you can select it from the list box. The name of the SQL Server is typically machine name\database server (for example, MyMachineName\SQLServerExpress). Also, a default SQL Server can be configured for the machine, and in that case, you can enter (local) to reference the default instance of the SQL Server on the machine. Click Next. The page shown in Figure 19-6 opens. 7. Enter the necessary security credentials to log into the server. The credentials will depend on how the particular SQL Server is configured. If the steps shown earlier were used to install the SQL Server, choose the option to use NT Authentication for the Windows User Account. If your server administrator has specified users using SQL Server authentication, select the proper option and type in the username and password. Click Next to continue. 8. The last setting to change is the default database (see Figure 19-7). 656 Chapter 19: Understanding Client-Server Development with VBA 47033c19.qxd:WroxProgRef 3/30/07 12:28 AM Page 656 Figure 19-6 Figure 19-7 The default database can be selected on a per-connection basis and different connections can reference different databases on the same server. The default database selection determines the database context for which commands are issued against the server. For example, if code is called to select records from a table in the NorthwindCS database, but the default database is the master database used by SQL Server, the query results in an error because the table doesn’t exist in the master database. Always specify a default database other than the master database to help prevent any accidental, unwanted modifications to the database. 9. For this example, select the NorthwindCS database (which you created earlier) from the default database list and then click Next. The remaining default option settings should be fine, so click Finish to complete the wizard. All of the options selected for the new connection are displayed, as shown in Figure 19-8. 657 Chapter 19: Understanding Client-Server Development with VBA 47033c19.qxd:WroxProgRef 3/30/07 12:28 AM Page 657 [...]... 673 470 33c19.qxd:WroxProgRef 3/30/ 07 12:28 AM Page 674 Chapter 19: Understanding Client-Server Development with VBA ‘ in the VBA editor and make sure a reference is set to: ‘ 1 Access 20 07: Microsoft Office 20 07 Access database engine Object Library ‘ 2 Access 2003 and older: Microsoft DAO 3.6 Object library ‘ Define Variables Dim strConnection As String Dim daoTableDef As DAO.TableDef ‘ This must reference. .. Additionally, there is no User-level security at the ADP file 670 470 33c19.qxd:WroxProgRef 3/30/ 07 12:28 AM Page 671 Chapter 19: Understanding Client-Server Development with VBA level for controlling permission to forms or reports Instead, data access is controlled at the server level However, the primary security mechanism at the ADP file level is to add a VBA project password or to convert the file to an ADE... = @P6 OR “OrderID” = @P7 OR “OrderID” = i @P8 OR “OrderID” = @P9 OR “OrderID” = @P10’, 10249, 10251, 10258, 10260, i 10265, 102 67, 10269, 10 270 , 10 274 , 10 275 ; select @P1 The sp_prepexec stored procedure prepares a SQL statement for use by subsequent queries and accepts parameter input to retrieve the first few rows (those with OrderID 10249-10 275 ) After that statement runs, Access can use the sp_execute... manipulate objects in the application when Access first tries to use the table or view Fortunately, it is easy to create a custom startup login form that looks similar to the one shown in Figure 19-16 and prompts for username and password Figure 19-16 672 470 33c19.qxd:WroxProgRef 3/30/ 07 12:28 AM Page 673 Chapter 19: Understanding Client-Server Development with VBA The form in Figure 19-16 is simple to... pass-through query in Access and the data they return is read only However, SQL Server 2005 and many other products have built in tools that are similar to the Query Builder and can generate SQL statements just as Access would It is important to note that in Access 20 07, SQL passthrough queries require that the database have code enabled before they can be run, but because this is a book about VBA, the application... illustrates reconnecting the ADP to the SQL Server: Public Sub ConnectADP() ‘ Define Variables 675 470 33c19.qxd:WroxProgRef 3/30/ 07 12:28 AM Page 676 Chapter 19: Understanding Client-Server Development with VBA Dim strConnect As String ‘ Required - This is the network name of the SQL Server ‘ “(local)“ can be used to reference a default SQL Server ‘ installation on the local machine Const strServerName =... connection If CurrentProject.IsConnected = False Then ‘ Error - Failed to Connect End If ‘ Clean up cnnTest.Close Set cnnTest = Nothing End Sub 677 470 33c19.qxd:WroxProgRef 3/30/ 07 12:28 AM Page 678 Chapter 19: Understanding Client-Server Development with VBA It’s easy to make a custom UDL file through the Windows interface Simply create a new blank text file, rename the extension to udl and then double-click... without direct access to the machine itself Access handles links differently depending on which type is chosen With a file DSN, Access stores the connectivity information in the MDB file and does not need to requery the DSN each time the table is opened With a machine DSN, Access must query the registry to retrieve the connectivity information with each new connection to the DSN 659 470 33c19.qxd:WroxProgRef... same instance of an ADP file cannot be opened by multiple users over a network You can work around this limitation by flagging the ADP file as read 671 470 33c19.qxd:WroxProgRef 3/30/ 07 12:28 AM Page 672 Chapter 19: Understanding Client-Server Development with VBA only, but that it is neither recommended nor supported by Microsoft and can potentially corrupt or cause problems with your ADP file A copy of... SQL Pass-through query in your Microsoft Access database Run the query to see the results that Access received when it ran the query When a linked table is opened in the Access application, Access retrieves the primary key information for the table as well as a few records, if any exist For example, double-click the dbo.Orders table in the Navigation pane, and Access sends the following query to the . Using ACE, Access 20 07 supports creat- ing the following file formats: ACCDB (Access 20 07 file format), MDB (Access 2000 and 2002-2003 file formats), ADP (Access Data Project), MDE (Access Complied. and reliability. Microsoft Office Access 20 07 features a brand new database engine: the Access Connectivity Engine (ACE) — also called the Access database engine. If you’ve used previous versions of Access, you are probably. Client-Server Development with VBA 470 33c19.qxd:WroxProgRef 3/30/ 07 12:28 AM Page 652 2002-2003 MDB file formats. While data in certain legacy formats can still be edited via Access 20 07, it should be noted