Cari di MySQL 
    MySQL Manual
Daftar Isi
(Sebelumnya) 22. Connectors and APIs22.2.5. Connector/Net Programming (Berikutnya)

22.2. MySQL Connector/Net

Connector/Net lets you easily develop .NET applications that require secure, high-performance data connectivity with MySQL. It implements the required ADO.NET interfaces and integrates into ADO.NET-aware tools. Developers can build applications using their choice of .NET languages. Connector/Net is a fully managed ADO.NET driver written in 100% pure C#.

Connector/Net includes full support for:

  • Features provided by MySQL Server up to and including MySQL Server version 5.5.

  • Large-packet support for sending and receiving rows and BLOBs up to 2 gigabytes in size.

  • Protocol compression, which enables compressing the data stream between the client and server.

  • Connections using TCP/IP sockets, named pipes, or shared memory on Windows.

  • Connections using TCP/IP sockets or Unix sockets on Unix.

  • The Open Source Mono framework developed by Novell.

  • Fully managed, does not utilize the MySQL client library.

This document is intended as a user's guide to Connector/Net and includes a full syntax reference. Syntax information is also included within the Documentation.chm file included with the Connector/Net distribution.

If you are using MySQL 5.0 or later, and Visual Studio as your development environment, you can also use the MySQL Visual Studio Plugin. The plugin acts as a DDEX (Data Designer Extensibility) provider: you can use the data design tools within Visual Studio to manipulate the schema and objects within a MySQL database. For more information, see Section 22.2.3, "Connector/Net Visual Studio Integration".

Note

Connector/Net 5.1.2 and later include the Visual Studio Plugin by default.

MySQL Connector/Net supports full versions of Visual Studio 2005, 2008, and 2010, although certain features are only available in Visual Studio 2010 when using MySQL Connector/Net version 6.3.2 and later. Note that MySQL Connector/Net does not currently support Express versions of Microsoft products, including Microsoft Visual Web Developer.

Key topics:

For release notes detailing the changes in each release of Connector/Net, see MySQL Connector/Net Release Notes.

As of Connector/Net 5.1.2, the Visual Studio Plugin is part of the main Connector/Net package. However, even for versions of Connector/Net older than 5.1.2, the Visual Studio Plugin release notes can be found at MySQL Connector/Net Release Notes.

22.2.1. Connector/Net Versions

There are several versions of Connector/Net available:

  • Connector/Net 6.6 includes support for MySQL Server 5.6, 5.5, 5.1, and 5.0. Important new features include stored procedure debugging in Microsoft Visual Studio, support for pluggable authentication including the ability to write you own authentication plugin, Entity Framework 4.3 Code First support, and enhancements to partial trust support to allow hosting services to deploy applications without installing the Connector/Net library in the GAC.

  • Connector/Net 6.5 includes support for MySQL Server 5.6, 5.5, 5.1, and 5.0. Important new features include interceptor classes for exceptions and commands, support for the MySQL 5.6 fractional seconds feature, better partial-trust support, and better IntelliSense, including auto-completion when editing stored procedures or .mysql files.

  • Connector/Net 6.4 includes support for MySQL Server 5.5, 5.1, and 5.0. Important new features include support for Windows authentication (when connecting to MySQL Server 5.5+), table caching on the client side, simple connection fail-over support, and improved SQL generation from the Entity Framework provider.

  • Connector/Net 6.3 includes support for MySQL Server 5.5, 5.1, and 5.0. Important new features include integration with Visual Studio 2010, such as availability of DDL T4 template for Entity Framework, and a custom MySQL SQL Editor. Other features include refactored transaction scope: Connector/Net now supports nested transactions in a scope where they use the same connection string.

  • Connector/Net 6.2 includes support for MySQL Server 5.5, 5.1, 5.0, and 4.1. Important new features include a new logging system and client SSL certificates.

  • Connector/Net 6.1 includes support for MySQL Server 5.5, 5.1, 5.0, and 4.1. Important new features include the MySQL Website Configuration Tool and a Session State Provider.

  • Connector/Net 6.0 includes support for MySQL Server 5.5, 5.1, 5.0, and 4.1.

    This version of Connector/Net is no longer supported.

  • Connector/Net 5.2 includes support for MySQL Server 5.5, 5.1, 5.0, and 4.1 features. Connector/Net 5.2 also includes support for a new membership/role provider, Compact Framework 2.0, a new stored procedure parser and improvements to GetSchema. Connector/Net 5.2 also includes the Visual Studio Plugin as a standard installable component.

    This version of Connector/Net is no longer supported.

  • Connector/Net 5.1 includes support for MySQL Server 5.5, 5.1, 5.0, 4.1, and 4.0 features. Connector/Net 5.1 also includes support for a new membership/role provider, Compact Framework 2.0, a new stored procedure parser and improvements to GetSchema. Connector/Net 5.1 also includes the Visual Studio Plugin as a standard installable component.

    This version of Connector/Net is no longer supported.

  • Connector/Net 5.0 includes support for MySQL Server 5.1, 5.0, 4.1 and 4.0 features. Connector/Net 5.0 also includes full support for the ADO.Net 2.0 interfaces and subclasses, includes support for the usage advisor and performance monitor (PerfMon) hooks.

    This version of Connector/Net is no longer supported.

  • Connector/Net 1.0 includes support for MySQL Server 5.0, 4.1, and 4.0 features, and full compatibility with the ADO.NET driver interface.

    This version of Connector/Net is no longer supported.

The latest source code for Connector/Net can be downloaded from the MySQL public Subversion server. For further details, see Section 22.2.2.3, "Installing Connector/Net from the Source Code".

The following table shows the .NET Framework version required, and the MySQL Server version supported by Connector/Net:

Table 22.19. Connector/Net Requirements for Related Products

Connector/Net versionADO.NET version supported.NET Framework version requiredMySQL Server version supportedCurrently supported
6.62.x+2.x+, 4.x+ for VS 2010 support5.6, 5.5, 5.1, 5.0Yes
6.52.x+2.x+, 4.x+ for VS 2010 support5.6, 5.5, 5.1, 5.0Yes
6.42.x+2.x+, 4.x+ for VS 2010 support5.6, 5.5, 5.1, 5.0Yes
6.32.x+2.x+, 4.x+ for VS 2010 support5.6, 5.5, 5.1, 5.0Yes
6.22.x+2.x+5.6, 5.5, 5.1, 5.0, 4.1Yes
6.12.x+2.x+5.6, 5.5, 5.1, 5.0, 4.1Yes
6.02.x+2.x+5.5, 5.1, 5.0, 4.1Critical issues only
5.22.x+2.x+5.5, 5.1, 5.0, 4.1No
5.12.x+2.x+5.5, 5.1, 5.0, 4.1, 4.0No
5.02.x+2.x+5.0, 4.1, 4.0No
1.01.x1.x5.0, 4.1, 4.0No

Note

Version numbers for MySQL products are formatted as X.Y.Z, where Z=0 indicates alpha, Z=1 indicates beta, and Z>=2 indicates GA. However, Windows tools (Control Panel, properties display) may show the version numbers as XX.YY.ZZ. For example, the official MySQL formatted version number 5.0.9 may be displayed by Windows tools as 5.00.09. The two versions are the same; only the number display format is different.

22.2.2. Installing Connector/Net

Connector/Net runs on any platform that supports the .NET framework. The .NET framework is primarily supported on recent versions of Microsoft Windows, and is supported on Linux through the Open Source Mono framework (see http://www.mono-project.com).

Connector/Net is available for download from http://dev.mysql.com/downloads/connector/net/.

22.2.2.1. Installing Connector/Net on Windows

On Windows, you can install either through a binary installation process or by downloading a zip file with the Connector/Net components.

Before installing, ensure that your system is up to date, including installing the latest version of the .NET Framework.

22.2.2.1.1. Installing Connector/Net using the Installer

Using the installer is the most straightforward method of installing Connector/Net on Windows and the installed components include the source code, test code and full reference documentation.

You install Connector/Net through a Windows Installer (.msi) installation package, which can install Connector/Net on all Windows operating systems. The MSI package is contained within a zip archive named mysql-connector-net-version.zip, where version indicates the Connector/Net version.

To install Connector/Net:

  1. Double-click the MSI installer file extracted from the zip you downloaded. Click Next to start the installation.

    Connector/Net Windows Installer - Welcome
  2. You must choose the type of installation to perform.

    Connector/Net Windows Installer - Installation type

    For most situations, the Typical installation is suitable. Click the Typical button and proceed to Step 5. A Complete installation installs all the available files. To conduct a Complete installation, click the Complete button and proceed to step 5. To customize your installation, including choosing the components to install and some installation options, click the Custom button and proceed to Step 3.

    The Connector/Net installer will register the connector within the Global Assembly Cache (GAC) - this will make the Connector/Net component available to all applications, not just those where you explicitly reference the Connector/Net component. The installer will also create the necessary links in the Start menu to the documentation and release notes.

  3. If you have chosen a custom installation, you can select the individual components to install, including the core interface component, supporting documentation (a CHM file) samples and examples, and the source code. Select the items, and their installation level, and then click Next to continue the installation.

    Note

    For Connector/Net 1.0.8 or lower and Connector 5.0.4 and lower the installer will attempt to install binaries for both 1.x and 2.x of the .NET Framework. If you only have one version of the framework installed, the connector installation may fail. If this happens, you can choose the framework version to be installed through the custom installation step.

    Connector/Net Windows Installer - Custom setup
  4. You will be given a final opportunity to confirm the installation. Click Install to copy and install the files onto your machine.

    Connector/Net Windows Installer - Confirming installation
  5. Once the installation has been completed, click Finish to exit the installer.

    Connector/Net Windows Installer - Finish installation

Unless you choose otherwise, Connector/Net is installed in C:\Program Files\MySQL\MySQL Connector Net X.X.X, where X.X.X is replaced with the version of Connector/Net you are installing. New installations do not overwrite existing versions of Connector/Net.

Depending on your installation type, the installed components will include some or all of the following components:

  • bin: Connector/Net MySQL libraries for different versions of the .NET environment.

  • docs: Connector/Net documentation in CHM format.

  • samples: Sample code and applications that use the Connector/Net component.

  • src: The source code for the Connector/Net component.

You may also use the /quiet or /q command-line option with the msiexec tool to install the Connector/Net package automatically (using the default options) with no notification to the user. Using this method the user cannot select options. Additionally, no prompts, messages or dialog boxes will be displayed.

C:\> msiexec /package connector-net.msi /quiet

To provide a progress bar to the user during automatic installation, use the /passive option.

22.2.2.1.2. Installing Connector/Net Using the Zip Packages

If you have problems running the installer, you can download a zip file without an installer as an alternative. That file is called mysql-connector-net-version-noinstall.zip. After downloading the zip archive, extract the files to a location of your choice.

The file contains the following directories:

  • bin: Connector/Net MySQL libraries for different versions of the .NET environment.

  • Docs: Connector/Net documentation in CHM format.

  • Samples: Sample code and applications that use the Connector/Net component.

Connector/Net 6.0.x has a different directory structure:

  • Assemblies: A collection of DLLs that make up the connector functionality.

  • Documentation: Connector/Net documentation in CHM format.

  • Samples: sample code and applications that use the Connector/Net component.

Another zip file available for download contains the source code distribution. This file is named mysql-connector-net-version-src.zip.

The file contains the following directories:

  • Documentation: Source files to build the documentation into the compiled HTML (CHM) format.

  • Installer: Source files to build the Connector/Net installer program.

  • MySql.Data: Source files for the core data provider.

  • MySql.VisualStudio: Source files for the Microsoft Visual Studio extensions.

  • MySql.Web: Source files for the web providers. This includes code for the membership provider, role provider and profile provider. These are used in ASP.NET web sites.

  • Samples: Source files for several example applications.

  • Tests: A spreadsheet listing test cases.

  • VisualStudio: Resources used by the Visual Studio plugin.

Finally, ensure that MySql.Data.dll is accessible to your program at build time (and run time). If using Microsoft Visual Studio, add MySql.Data as a Reference to your project.

Note

If using MySQL Connector/Net 6.3.5 and above, the MySql.Data.dll file provided will work with both .NET Framework 2.x and 4.x.

22.2.2.2. Installing Connector/Net on Unix with Mono

There is no installer available for installing the Connector/Net component on your Unix installation. Before installing, ensure that you have a working Mono project installation. To test whether your system has Mono installed, enter:

shell> mono --version

The version of the Mono JIT compiler is displayed.

To compile C# source code, make sure a Mono C# compiler is installed. Note that there are two Mono C# compilers available, mcs, which accesses the 1.0-profile libraries, and gmcs, which accesses the 2.0-profile libraries.

To install Connector/Net on Unix/Mono:

  1. Download the mysql-connector-net-version-noinstall.zip and extract the contents to a directory of your choice, for example: ~/connector-net/.

  2. In the directory where you unzipped the connector to, change into the bin subdirectory. Ensure the file MySql.Data.dll is present. This filename is case-sensitive.

  3. You must register the Connector/Net component, MySql.Data, in the Global Assembly Cache (GAC). In the current directory enter the gacutil command:

    root-shell> gacutil /i MySql.Data.dll

    This will register MySql.Data into the GAC. You can check this by listing the contents of /usr/lib/mono/gac, where you will find MySql.Data if the registration has been successful.

You are now ready to compile your application. You must ensure that when you compile your application you include the Connector/Net component using the -r: command-line option. For example:

shell> gmcs -r:System.dll -r:System.Data.dll -r:MySql.Data.dll HelloWorld.cs

Note, the assemblies that are referenced depend on the requirements of the application, but applications using Connector/Net must provide -r:MySql.Data as a minimum.

You can further check your installation by running the compiled program, for example:

shell> mono HelloWorld.exe

22.2.2.3. Installing Connector/Net from the Source Code

Caution

Read this section only if you are interested in helping us test our new code. If you just want to get Connector/Net up and running on your system, use a standard release distribution.

Obtaining the Source Code

To obtain the most recent development source tree, first download and install Bazaar. You can obtain Bazaar from the Bazaar VCS Website. Bazaar is supported by any platform that supports Python, and is therefore compatible with any Linux, Unix, Windows or Mac OS X host. Instructions for downloading and installing Bazaar on the different platforms are available on the Bazaar Web site.

The most recent development source tree is available from our public Subversion trees at http://dev.mysql.com/tech-resources/sources.html.

To check out out the Connector/Net sources, change to the directory where you want the copy of the Connector/Net tree to be stored, then use the following command:

shell> bzr branch lp:connectornet/trunk

To download a specific version of Connector/Net, specify the version number instead of trunk. For example, to obtain a copy of the 6.0 version of the source tree:

shell> bzr branch lp:connectornet/6.0

Source packages are also available on the downloads page.

Building the Source Code on Windows

The following procedure can be used to build the connector on Microsoft Windows.

  • Obtain the source code, either from the Subversion server, or through one of the prepared source code packages.

  • Navigate to the root of the source code tree.

  • A Microsoft Visual Studio 2005 solution file is available to build the connector, this is called MySQL-VS2005.sln. Click this file to load the solution into Visual Studio.

  • Select Build, Build Solution from the main menu to build the solution.

Building the Source Code on Unix

Support for building Connector/Net on Mono/Unix is currently not available.

22.2.3. Connector/Net Visual Studio Integration

When MySQL Connector/Net is installed on Microsoft Windows, Visual Studio integration components are also installed and initialized. This enables the developer to work seamlessly with MySQL Connector/Net in the familiar Visual Studio environment, as described in the following sections of the manual.

MySQL Connector/Net supports Visual Studio versions 2005, 2008, and 2010. However, only MySQL Connector/Net version 6.3 and higher fully integrate with Visual Studio 2010, although applications using earlier versions of the connector can be built with the Visual Studio 2010 environment using .NET 2.x frameworks.

Visual Studio 2010 support was introduced with MySQL Connector/Net 6.3.2. From version 6.3.2 the connector ships with both .NET 2.x and .NET 4.x versions of the entity framework support files, mysql.data.ef.dll and mysql.visualstudio.dll. The .NET 4.x versions are required to enable new integration features supported in Visual Studio 2010, including:

  • New DDL T4 template for the Entity Framework (EF) - This enables developers to design an EF model from scratch and use the native Visual Studio 2010 facility to generate MySQL DDL from that model. This is done by creating the model, and with the model open, choosing the SSDLToMySQL template in the properties window. The correct DDL is then generated. The developer can then save this code as a .mysql file in their project and execute it against the MySQL server.

  • New SQL Editor - A new SQL editor lets you connect to a MySQL server to execute SQL. This is activated by creating a new file with a .mysql extension. A new template lets you create files with this file type using the Visual Studio 2010 main menu item File, New. Note that the MySQL SQL Editor is also available in Visual Studio 2005 and 2008.

As of Connector/Net 5.1.2, the Visual Studio Plugin is part of the main Connector/Net package. However, even for versions of Connector/Net older than 5.1.2, the Visual Studio Plugin release notes can be found at MySQL Connector/Net Release Notes.

22.2.3.1. Making a Connection

Once the connector is installed, you can use it to create, modify, and delete connections to MySQL databases. To create a connection with a MySQL database, perform the following steps:

  • Start Visual Studio, and open the Server Explorer window (View, Server Explorer option in the main Visual Studio menu, or Control+W, L keyboard shortcuts).

  • Right-click the Data Connections node, and choose the Add Connection... menu item.

  • Add Connection dialog opens. Press the Change button to choose MySQL Database as a data source.

    Figure 22.1. Add Connection Context Menu

    Add Connection Context Menu
  • Change Data Source dialog opens. Choose MySQL Database in the list of data sources (or the <other> option, if MySQL Database is absent), and then choose .NET Framework Data Provider for MySQL in the combo box of data providers.

    Figure 22.2. Choose Data Source

    Choose Data Source
  • Input the connection settings: the server host name (for example, localhost if the MySQL server is installed on the local machine), the user name, the password, and the default schema name. Note that you must specify the default schema name to open the connection.

    Figure 22.3. Add Connection Dialog

    Add Connection Dialog
  • You can also set the port to connect with the MySQL server by pressing the Advanced button. To test connection with the MySQL server, set the server host name, the user name, and the password, and press the Test Connection button. If the test succeeds, the success confirmation dialog opens.

  • After you set all settings and test the connection, press OK. The newly created connection is displayed in Server Explorer. Now you can work with the MySQL server through standard Server Explorer GUI.

    Figure 22.4. New Data Connection

    New Data Connection

After the connection is successfully established, all settings are saved for future use. When you start Visual Studio for the next time, open the connection node in Server Explorer to establish a connection to the MySQL server again.

To modify and delete a connection, use the Server Explorer context menu for the corresponding node. You can modify any of the settings by overwriting the existing values with new ones. Note that the connection may be modified or deleted only if no active editor for its objects is opened: otherwise, you may lose your data.

22.2.3.2. Using IntelliSense in the SQL Editor

IntelliSense support is available starting in Connector/Net 6.5. Once you have established a connection, for example, using the Connect to MySql toolbar button, you can get autocompletion as you type, or by pressing Control+J. Depending on the context, the autocompletion dialog can show the list of available tables, table columns, or stored procedures (with the routine's signature as a tooltip). Typing some characters before pressing Control+J filters the choices to those items starting with that prefix.

22.2.3.3. Editing Tables

Connector/Net contains a table editor, which enables the visual creation and modification of tables.

The Table Designer can be accessed through a mouse action on table-type node of Server Explorer. To create a new table, right-click the Tables node (under the connection node) and choose the Create Table command from the context menu.

To modify an existing table, double-click the node of the table to modify, or right-click this node and choose the Design item from the context menu. Either of the commands opens the Table Designer.

The table editor is implemented in the manner of the well-known Query Browser Table Editor, but with minor differences.

Figure 22.5. Editing New Table


Table Designer consists of the following parts:

  • Columns Editor - a data grid on top of the Table Designer. Use the Columns grid for column creation, modification, and deletion.

  • Indexes tab - a tab on bottom of the Table Designer. Use the Indexes tab for indexes management.

  • Foreign Keys tab - a tab on bottom of the Table Designer. Use the Foreign Keys tab for foreign keys management.

  • Column Details tab - a tab on bottom of the Table Designer. Use the Column Details tab to set advanced column options.

  • Properties window - a standard Visual Studio Properties window, where the properties of the edited table are displayed. Use the Properties window to set the table properties.

Each of these areas is discussed in more detail in subsequent sections.

To save changes you have made in the Table Designer, use either Save or Save All button of the Visual Studio main toolbar, or press Control+S. If you have not already named the table, you will be prompted to do so.

Figure 22.6. Choose Table Name

Choose Table Name

Once the table is created, you can view it in the Server Explorer.

Figure 22.7. Newly Created Table

Newly Created Table

The Table Designer main menu lets you set a primary key column, edit relationships such as foreign keys, and create indexes.

Figure 22.8. Table Designer Main Menu

Table Designer Main Menu

22.2.3.3.1. Column Editor

You can use the Column Editor to set or change the name, data type, default value, and other properties of a table column. To set the focus to a needed cell of a grid, use the mouse click. Also you can move through the grid using Tab and Shift+Tab keys.

To set or change the name, data type, default value and comment of a column, activate the appropriate cell and type the desired value.

To set or unset flag-type column properties (NOT NULL, auto incremented, flags), check or uncheck the corresponding check boxes. Note that the set of column flags depends on its data type.

To reorder columns, index columns or foreign key columns in the Column Editor, select the whole column to reorder by clicking the selector column on the left of the column grid. Then move the column by using Control+Up (to move the column up) or Control+Down (to move the column down) keys.

To delete a column, select it by clicking the selector column on the left of the column grid, then press the Delete button on a keyboard.

22.2.3.3.2. Editing Indexes

Indexes management is performed using the Indexes/Keys dialog.

To add an index, select Table Designer, Indexes/Keys... from the main menu, and click Add to add a new index. You can then set the index name, index kind, index type, and a set of index columns.

Figure 22.9. Indexes Dialog

Indexes Dialog

To remove an index, select it in the list box on the left, and click the Delete button.

To change index settings, select the needed index in the list box on the left. The detailed information about the index is displayed in the panel on the right hand side. Change the desired values.

22.2.3.3.3. Editing Foreign Keys

You manage foreign keys for InnoDB tables using the Foreign Key Relationships dialog.

To add a foreign key, select Table Designer, Relationships... from the main menu. This displays the Foreign Key Relationship dialog. Click Add. You can then set the foreign key name, referenced table name, foreign key columns, and actions upon update and delete.

To remove a foreign key, select it in the list box on the left, and click the Delete button.

To change foreign key settings, select the required foreign key in the list box on the left. The detailed information about the foreign key is displayed in the right hand panel. Change the desired values.

Figure 22.10. Foreign Key Relationships Dialog

Foreign Key Relationships Dialog

22.2.3.3.4. Column Properties

The Column Properties tab can be used to set column options. In addition to the general column properties presented in the Column Editor, in the Column Properties tab you can set additional properties such as Character Set, Collation and Precision.

22.2.3.3.5. Table Properties

To bring up Table Properties select the table and right-click to activate the context menu. Select Properties. The Table Properties dockable window will be displayed.

Figure 22.11. Table Properties Menu Item


The following table properties can be set:

  • Auto Increment.

  • Average Row Length.

  • Character Set.

  • Collation.

  • Comment.

  • Data Directory.

  • Index Directory.

  • Maximum Rows.

  • Minimum Rows.

  • Name.

  • Row Format.

  • Schema.

  • Storage Engine. Note that in MySQL 5.5 and higher, the default storage engine for new tables is InnoDB. See Section 14.3.1, "InnoDB as the Default MySQL Storage Engine" for more information about the choice of storage engine, and considerations if you convert existing tables to InnoDB.

The property Schema is read-only.

Figure 22.12. Table Properties


22.2.3.4. Editing Views

To create a new view, right-click the Views node under the connection node in Server Explorer. From the node's context menu, choose the Create View command. This command opens the SQL Editor.

Figure 22.13. Editing View SQL

Editing View SQL

You can then enter the SQL for your view.

Figure 22.14. View SQL Added

View SQL Added

To modify an existing view, double-click a node of the view to modify, or right-click this node and choose the Alter View command from a context menu. Either of the commands opens the SQL Editor.

All other view properties can be set in the Properties window. These properties are:

  • Catalog

  • Check Option

  • Definer

  • Definition

  • Definer

  • Is Updatable

  • Name

  • Schema

  • Security Type

Some of these properties can have arbitrary text values, others accept values from a predefined set. In the latter case, set the desired value with an embedded combobox.

The properties Is Updatable and Schema are readonly.

To save changes you have made, use either Save or Save All buttons of the Visual Studio main toolbar, or press Control+S.

Figure 22.15. View SQL Saved


22.2.3.5. Editing Stored Procedures and Functions

To create a new stored procedure, right-click the Stored Procedures node under the connection node in Server Explorer. From the node's context menu, choose the Create Routine command. This command opens the SQL Editor.

Figure 22.16. Edit Stored Procedure SQL

Edit Stored Procedure SQL

To create a new stored function, right-click the Functions node under the connection node in Server Explorer. From the node's context menu, choose the Create Routine command.

To modify an existing stored routine (procedure or function), double-click the node of the routine to modify, or right-click this node and choose the Alter Routine command from the context menu. Either of the commands opens the SQL Editor.

To create or alter the routine definition using SQL Editor, type this definition in the SQL Editor using standard SQL. All other routine properties can be set in the Properties window. These properties are:

  • Body

  • Catalog

  • Comment

  • Creation Time

  • Data Access

  • Definer

  • Definition

  • External Name

  • External Language

  • Is Deterministic

  • Last Modified

  • Name

  • Parameter Style

  • Returns

  • Schema

  • Security Type

  • Specific Name

  • SQL Mode

  • SQL Path

  • Type

Some of these properties can have arbitrary text values, others accept values from a predefined set. In the latter case, set the desired value using the embedded combo box.

You can also set all the options directly in the SQL Editor, using the standard CREATE PROCEDURE or CREATE FUNCTION statement. However, it is recommended to use the Properties window instead.

To save changes you have made, use either Save or Save All buttons of the Visual Studio main toolbar, or press Control+S.

Figure 22.17. Stored Procedure SQL Saved


To observe the runtime behavior of a stored routine and debug any problems, use the Stored Procedure Debugger (available in Connector/Net 6.6 and higher). See Section 22.2.3.8, "Debugging Stored Procedures and Functions" for details.

22.2.3.6. Editing Triggers

To create a new trigger, right-click the node of the table in which to add the trigger. From the node's context menu, choose the Create Trigger command. This command opens the SQL Editor.

To modify an existing trigger, double-click the node of the trigger to modify, or right-click this node and choose the Alter Trigger command from the context menu. Either of the commands opens the SQL Editor.

To create or alter the trigger definition using SQL Editor, type the trigger statement in the SQL Editor using standard SQL.

Note

Enter only the trigger statement, that is, the part of the CREATE TRIGGER query that is placed after the FOR EACH ROW clause.

All other trigger properties are set in the Properties window. These properties are:

  • Definer

  • Event Manipulation

  • Name

  • Timing

Some of these properties can have arbitrary text values, others accept values from a predefined set. In the latter case, set the desired value using the embedded combo box.

The properties Event Table, Schema, and Server in the Properties window are read-only.

To save changes you have made, use either Save or Save All buttons of the Visual Studio main toolbar, or press Control+S. Before changes are saved, you will be asked to confirm the execution of the corresponding SQL query in a confirmation dialog.

To observe the runtime behavior of a stored routine and debug any problems, use the Stored Procedure Debugger (available in Connector/Net 6.6 and higher). See Section 22.2.3.8, "Debugging Stored Procedures and Functions" for details.

22.2.3.7. Editing User Defined Functions (UDF)

To create a new User Defined Function (UDF), right-click the UDFs node under the connection node in Server Explorer. From the node's context menu, choose the Create UDF command. This command opens the UDF Editor.

To modify an existing UDF, double-click the node of the UDF to modify, or right-click this node and choose the Alter UDF command from the context menu. Either of these commands opens the UDF Editor.

The UDF editor enables you to set the following properties:

  • Name

  • So-name (DLL name)

  • Return type

  • Is Aggregate

There are text fields for both names, a combo box for the return type, and a check box to indicate if the UDF is aggregate. All these options are also accessible using the Properties window.

The property Server in the Properties window is read-only.

To save changes you have made, use either Save or Save All buttons of the Visual Studio main toolbar, or press Control+S. Before changes are saved, you will be asked to confirm the execution of the corresponding SQL query in a confirmation dialog.

To observe the runtime behavior of a stored routine and debug any problems, use the Stored Procedure Debugger (available in Connector/Net 6.6 and higher). See Section 22.2.3.8, "Debugging Stored Procedures and Functions" for details.

22.2.3.8. Debugging Stored Procedures and Functions

The stored procedure debugger, new in Connector/Net 6.6, provides facilities for setting breakpoints, stepping into individual statements (Step Into, Step Out, Step Over), evaluating and changing local variable values, evaluating breakpoints, and other typical debugging tasks.

Installing the Debugger

To enable the stored procedure debugger, install Connector/Net 6.6 or higher and choose the Complete option.

Privileges

The debugger recreates at the start of each debug session a serversidedebugger database in your server. This database helps to track the instrumented code and implement observability logic in the debugged routine. Your current connection needs to have privileges to create that database, and its associated stored routines, functions, and tables.

The debugger makes changes behind the scenes to temporarily add instrumentation code to the stored routines that you debug. You must have the ALTER ROUTINE privilege for each stored procedure, function, or trigger that you debug. (Including procedures and functions that are called, and triggers that are fired, by a procedure that you are debugging.)

Starting the Debugger

To start the debugger, follow these steps:

  • Choose a connection in the Visual Studio Server Explorer.

    Figure 22.18. Connection Dialog

    Connection Dialog

  • Expand the Stored Procedures folder. Only stored procedures can be debugged directly. To debug a user-defined function, create a stored procedure that calls the function.

  • Click on a stored procedure node, then right-click and from the context menu choose Debug Routine.

    Figure 22.19. Choose a Stored Routine to Debug

    Screen capture of stored procedure debugger, showing how to choose a stored routine to debug

At this point, Visual Studio switches to debug mode, opening the source code of the routine being debugged in step mode, positioned on the first statement.

If the initial routine you debug has one or more arguments, a popup will show up with a grid (a row per each argument and three columns: one for the argument, one for the argument value (this is editable) and one for nullifying that argument value (a checkbox)). After setting up all the argument values, you can press OK to start the debug session, or Cancel to cancel the debug session.

Figure 22.20. Setting Arguments (1 of 2)

Setting Arguments (1 of 2)

Figure 22.21. Setting Arguments (2 of 2)

Setting Arguments (2 of 2)

How the Debugger Works

To have visibility into the internal workings of a stored routine, the debugger prepares a special version of the procedure, function, or trigger being debugged, instrumented with extra code to keep track of the current line being stepped into and the values of all the local variables. Any other stored procedures, functions, or triggers called from the routine being debugged are instrumented the same way. The debug versions of the routines are prepared for you automatically, and when the debug session ends (by either pressing F5 or Shift+F5), the original versions of the routines are automatically restored.

A copy of the original version of each instrumented routine (the version without instrumentation) is stored in the AppData\Roaming\MySqlDebuggerCache folder for the current Windows user (the path returned by calling System.Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) in .NET, plus appending MySqlDebuggerCache. There is one file for each instrumented routine, named routine_name.mysql. For example, in Windows 7, for a user named fergs, the path is C:\Users\fergs\AppData\Roaming\MySqlDebuggerCache.

Two threads are used, one for the debugger and one for the routine being debugged. The threads run in strict alternation, switching between the debugger and the routine as each statement is executed in the stored routine.

Basic Debugging Operations

The debugger has the same look and feel as the standard Visual Studio debuggers for C#, VB.NET or C++. In particular, the following are true:

Locals and Watches

  • To show the Locals tab, choose the menu item Debug -> Windows -> Locals.

    The Locals tab lists all the variables available in the current scope: variables defined with DECLARE at any point in the routine, argument parameters, and session variables that are referenced.

  • If the last step operation changes the value of a local, its value will be highlighted in red (until another statement is executed or stepped.

  • You can change the value of any local.

  • To show the Watch tab, choose the menu item Debug -> Windows -> Watch.

    To define a watch, type any valid MySQL expression, optionally including function calls. If the watch evaluation makes sense in the current context (current stack frame), it will show its value, otherwise it will show an error message in the same row the watch was defined.

  • When debugging a trigger, in addition to any locals declared or session variables referenced, the new and old object (when aplicable) will be listed. For example in a trigger for INSERT, for a table defined like:

    create table t1( id int, myname varchar( 50 ));

    Figure 22.22. Debugging a Trigger

    Debugging a Trigger

Call Stack

  • To show the Call Stack tab, choose the menu item Debug -> Windows -> Call Stack.

  • The stack trace (in the Call Stack tab) will list all the stack traces, one for each routine invocation. The one with a yellow mark is the current stepping point. Clicking in another will activate in the editor the tab for that routine source, highlighting in green the last statement stepped.

    Figure 22.23. Call Stack

    Call Stack

Stepping

  • Stepping of a new routine starts in the first executable instruction (excluding declares, handlers, cursor declarations, and so on).

    Figure 22.24. Debug Stepping


    Figure 22.25. Function Stepping (1 of 2)

    Function Stepping (1 of 2)

    Figure 22.26. Function Stepping (2 of 2)

    Function Stepping (2 of 2)

  • To step into the code of a condition handler, the condition must be triggered in the rest of the MySQL routine.

  • The next statement to be executed is highlighted in yellow.

  • To continue stepping, you can choose between Step Into (by pressing F11), Step Out (by pressing F10) or Step Over (by presssing Shift+F11).

  • You can step out of any of functions, triggers or stored procedures. If you step from the main routine, it will run that routine to completion and finish the debug session.

  • You can step over stored procedure calls, stored functions, and triggers. (To step over a trigger, step over the statement that would cause the trigger to fire.)

  • When stepping into a single statement, the debugger will step into each individual function invoked by that statement and each trigger fired by that statement. The order in which they are debugged is the same order in which the MySQL server executes them.

  • You can step into triggers triggered from INSERT, DELETE, UPDATE, and REPLACE statements.

  • Also, the number of times you enter into a stored function or trigger depends on how many rows are evaluated by the function or affected by the trigger. For example, if you press F11 (Step Into) into an UPDATE statement that modifies three rows (calling a function for a column in the SET clause, thus invoking the function for each of the three rows), you will step into into that function three times in succession, once for each of the rows. You can accelerate this debug session by disabling any breakpoints defined in the given stored function and pressing Shift+F11 to step out. In this example, the order in which the different instances of the stored function are debugged is server-specific: the same order used by the current MySQL server instance to evaluate the three function invocations.

Breakpoints

  • To show the Breakpoints tab, choose the menu item Debug -> Windows -> Breakpoints.

  • The Breakpoints tab will show all the breakpoints defined. From here, you can enable and disable breakpoints one by one or all at once (using the toolbar on top of the Breakpoints tab).

  • You can define new breakpoints only in the middle of a debug session. Click in the left gray border of any MySQL editor, or click anywhere in a MySQL editor and press F9. In the familiar Visual Studio way, you press F9 once to create a breakpoint in that line, and press it again to remove that breakpoint.

  • Once a breakpoint is defined, it will appear enabled (as filled red circle left to the current row if that line is a valid statement to put a breakpoint) or disabled (as a non-filled red circle left to the current row if that row is not valid to put a breakpoint).

  • To define conditional breakpoints, after creating the breakpoint, right click in the red dot and choose Condition.... There you can put any valid MySQL expression and state if the condition is Is True or Has changed. The former will trigger the breakpoint every time the condition is true, the latter every time the condition value has changed. (If you define a conditional breakpoint, it is not enough to step into the line with the breakpoint defined to trigger such a breakpoint.)

    Figure 22.27. Conditional Breakpoints

    Conditional Breakpoints

    Figure 22.28. Expressions and Breakpoints


  • To define pass count breakpoints, after creating the breakpoint, right click in the red dot and choose Hit Count.... In the popup dialog, define the specific condition to set. For example, break when the hit count is equal to and a value 3 will trigger the breakpoint the third time it is hit.

Other Features
  • To abort the debug session (and the execution of the current call stack of routines), press Shift+F5.

  • To run the routine to completion (or until next breakpoint hit), press F5.

  • For all functionality you can use (in addition to the shortcuts documented), see the options in the Debug menu of Visual Studio.

Limitations
  • Code being debugged must not use get_lock or release_lock MySQL functions, since they are used internally by the debugger infrastructure to synchronize the debugger and the debugged routine.

  • Code being debugged must avoid using any transaction code (START TRANSACTION, COMMIT, ROLLBACK) due to the possibility of wiping out the contents of the debugger tables. (This limitation may be removed in the future).

  • You cannot debug the routines in the serversidedebugger database.

  • The MySQL server running the routine being debugged can be any version between 5.0 and 5.6, running on Windows, Linux, or any other supported platform.

  • We recommend always running debug sessions on test and development servers, rather than against a MySQL production server, because debugging can cause temporary performance issues or even deadlocks. The instrumented versions of the routines being debugged use locks, that the rest of the production code may not be aware of.

Keyboard Shortcuts

The following list summarizes the keyboard shortcuts for debugging:

  • F9 Toggles breakpoints

  • F11: Step into once

  • F10: Step over once

  • Shift+F11: Step out once

  • F5: Run

  • Shift+F5: Abort current debug session

22.2.3.9. Cloning Database Objects

Tables, views, stored procedures, and functions can be cloned using the appropriate Clone command from the context menu: Clone Table, Clone View, Clone Routine. The clone commands open the corresponding editor for a new object: the Table Editor for cloning a table, and the SQL Editor for cloning a view or a routine.

The editor is filled with values of the original object. You can modify these values in the usual manner.

To save the cloned object, use either Save or Save All buttons of the Visual Studio main toolbar, or press Control+S. Before changes are saved, you will be asked to confirm the execution of the corresponding SQL query in a confirmation dialog.

22.2.3.10. Dropping Database Objects

Tables, views, stored routines, triggers, and UDFs can be dropped with the appropriate Drop command selected from its context menu: Drop Table, Drop View, Drop Routine, Drop Trigger, Drop UDF.

You will be asked to confirm the execution of the corresponding drop query in a confirmation dialog.

You can only drop a single object at a time.

22.2.3.11. Using the ADO.NET Entity Framework

Connector/Net 6.0 introduced support for the ADO.NET Entity Framework. ADO.NET Entity Framework was included with .NET Framework 3.5 Service Pack 1, and Visual Studio 2008 Service Pack 1. ADO.NET Entity Framework was released on 11th August 2008.

ADO.NET Entity Framework provides an Object Relational Mapping (ORM) service, mapping the relational database schema to objects. The ADO.NET Entity Framework defines several layers, these can be summarized as:

  • Logical - this layer defines the relational data and is defined by the Store Schema Definition Language (SSDL).

  • Conceptual - this layer defines the .NET classes and is defined by the Conceptual Schema Definition Language (CSDL)

  • Mapping - this layer defines the mapping from .NET classes to relational tables and associations, and is defined by Mapping Specification Language (MSL).

Connector/Net integrates with Visual Studio 2008 to provide a range of helpful tools to assist the developer.

A full treatment of ADO.NET Entity Framework is beyond the scope of this manual. If you are unfamiliar with ADO.NET, review the Microsoft ADO.NET Entity Framework documentation.

Tutorials on getting started with ADO.NET Entity Framework are available. See Section 22.2.4.5, "Tutorial: Using an Entity Framework Entity as a Windows Forms Data Source" and Section 22.2.4.6, "Tutorial: Databinding in ASP.NET using LINQ on Entities".

22.2.3.12. MySQL Website Configuration Tool

MySQL Connector/Net 6.1 introduced the MySQL Website Configuration Tool. This is a facility available in Visual Studio that enables you to configure the Membership, Role, Session State and Profile Provider, without editing configuration files. You set your configuration options within the tool, and the tool modifies your web.config file accordingly.

The MySQL Website Configuration Tool appears as a small icon on the Solution Explorer toolbar in Visual Studio, as show by the following screenshot:

Figure 22.29. MySQL Website Configuration Tool

MySQL Website Configuration Tool

Clicking the Website Configuration Tool icon launches the wizard and displays the first screen:

Figure 22.30. MySQL Website Configuration Tool - Membership

MySQL Website Configuration Tool - Membership

This allows you to enable use of the MySQL Membership Provider. Click the check box to enable this. You can now enter the name of the application that you are creating the configuration for. You can also enter a description for the application.

You can then click the Edit... button to launch the Connection String Editor:

Figure 22.31. MySQL Website Configuration Tool - Connection String Editor

MySQL Website Configuration Tool - Connection String Editor

Note that if you have already defined a connection string for the providers manually in web.config, or previously using the tool, this will be automatically loaded and displayed, and can then be modified in this dialog.

You can also ensure that the necessary schemas are created automatically for you by selecting the Autogenerate Schema check box. These schemas are used to store membership information. The database used to storage is the one specified in the connection string.

You can also ensure that exceptions generated by the application will be written to the Windows event log by selecting the Write exceptions to event log check box.

Clicking the Advanced... button launches a dialog that enables you to set Membership Options. These options dictate such variables as password length required when a user signs up, whether the password is encrypted and whether the user can reset their password or not.

Figure 22.32. MySQL Website Configuration Tool - Advanced Options

MySQL Website Configuration Tool - Advanced Options

Once information has been set up as required for configuration of the Membership Provider, the Next button can be clicked to display the Roles Provider screen:

Figure 22.33. MySQL Website Configuration Tool - Roles

MySQL Website Configuration Tool - Roles

Again the connection string can be edited, a description added and Autogenerate Schema can be enabled before clicking Next to go to the Profiles Provider screen:

Figure 22.34. MySQL Website Configuration Tool - Profiles

MySQL Website Configuration Tool - Profiles

This screen display similar options to the previous screens.

Click Next to proceed to the Session State configuration page:

Figure 22.35. MySQL Website Configuration Tool - Session State

MySQL Website Configuration Tool - Session State

Once you have set up the Session State Provider as required, click Finish to exit the wizard.

At this point, select the Authentication Type to From Internet. Launch the ASP.NET Configuration Tool and select the Security tab. Click the Select authentication type link and ensure that the From the internet radio button is selected. You can now examine the database you created to store membership information. All the necessary tables will have been created for you:

Figure 22.36. MySQL Website Configuration Tool - Tables

MySQL Website Configuration Tool - Tables

22.2.3.13. MySQL SQL Editor

MySQL Connector/Net 6.3.2 introduced a new MySQL SQL Editor. The easiest way to invoke the editor is by selecting the New, File menu item from the Visual Studio main menu. This displays the New File dialog:

Figure 22.37. MySQL SQL Editor - New File

MySQL SQL Editor - New File

From the New File dialog, select the MySQL template, and then double-click the MySQL SQL Script document, or click the Open button.

The MySQL SQL Editor will be displayed. You can now enter SQL code as required, or connect to a MySQL server. Click the Connect to MySQL button in the MySQL SQL Editor toolbar. You can enter the connection details into the Connect to MySQL dialog that is displayed. You can enter the server name, user ID, password and database to connect to, or click the Advanced button to select other connection string options. Click the Connect button to connect to the MySQL server. To execute your SQL code against the server, click the Run SQL button on the toolbar.

Figure 22.38. MySQL SQL Editor - Query

MySQL SQL Editor - Query

The results from any queries are displayed on the Results tab. Any errors are displayed on the Messages tab.

22.2.3.14. DDL T4 Template Macro

MySQL Connector/Net 6.3 introduced the ability to convert an Entity Framework model to MySQL DDL code. Starting with a blank model, you can develop an entity model in Visual Studio's designer. Once the model is created, you can select the model's properties, and in the Database Script Generation category of the model's properties, the property DDL Generation can be found. Select the value SSDLToMySQL.tt(VS) from the drop-down listbox.

Figure 22.39. DDL T4 Template Macro - Model Properties


Right-clicking the model design area displays a context-sensitive menu. Selecting Generate Database from Model from the menu displays the Generate Database Wizard. The wizard can then be used to generate MySQL DDL code.

Figure 22.40. DDL T4 Template Macro - Generate Database Wizard

DDL T4 Template Macro - Generate Database Wizard

22.2.4. Connector/Net Tutorials

The following tutorials illustrate how to develop MySQL programs using technologies such as Visual Studio, C#, ASP.NET, and the .NET and Mono frameworks. Work through the first tutorial to verify that you have the right software components installed and configured, then choose other tutorials to try depending on the features you intend to use in your applications.

22.2.4.1. Tutorial: An Introduction to Connector/Net Programming

This section provides a gentle introduction to programming with Connector/Net. The example code is written in C#, and is designed to work on both Microsoft .NET Framework and Mono.

This tutorial is designed to get you up and running with Connector/Net as quickly as possible, it does not go into detail on any particular topic. However, the following sections of this manual describe each of the topics introduced in this tutorial in more detail. In this tutorial you are encouraged to type in and run the code, modifying it as required for your setup.

This tutorial assumes you have MySQL and Connector/Net already installed. It also assumes that you have installed the World example database, which can be downloaded from the MySQL Documentation page. You can also find details on how to install the database on the same page.

Note

Before compiling the example code, make sure that you have added References to your project as required. The References required are System, System.Data and MySql.Data.

22.2.4.1.1. The MySqlConnection Object

For your Connector/Net application to connect to a MySQL database, it must establish a connection by using a MySqlConnection object.

The MySqlConnection constructor takes a connection string as one of its parameters. The connection string provides necessary information to make the connection to the MySQL database. The connection string is discussed more fully in Section 22.2.5.1, "Connecting to MySQL Using Connector/Net". For a list of supported connection string options, see Section 22.2.6, "Connector/Net Connection String Options Reference".

The following code shows how to create a connection object:

using System;using System.Data;using MySql.Data;using MySql.Data.MySqlClient;public class Tutorial1{ public static void Main() { string connStr = "server=localhost;user=root;database=world;port=3306;password=******;"; MySqlConnection conn = new MySqlConnection(connStr); try { Console.WriteLine("Connecting to MySQL..."); conn.Open(); // Perform database operations } catch (Exception ex) { Console.WriteLine(ex.ToString()); } conn.Close(); Console.WriteLine("Done."); }}

When the MySqlConnection constructor is invoked, it returns a connection object, which is used for subsequent database operations. Open the connection before any other operations take place. Before the application exits, close the connection to the database by calling Close on the connection object.

Sometimes an attempt to perform an Open on a connection object can fail, generating an exception that can be handled using standard exception handling code.

In this section you have learned how to create a connection to a MySQL database, and open and close the corresponding connection object.

22.2.4.1.2. The MySqlCommand Object

Once a connection has been established with the MySQL database, the next step is do carry out the desired database operations. This can be achieved through the use of the MySqlCommand object.

You will see how to create a MySqlCommand object. Once it has been created, there are three main methods of interest that you can call:

  • ExecuteReader - used to query the database. Results are usually returned in a MySqlDataReader object, created by ExecuteReader.

  • ExecuteNonQuery - used to insert and delete data.

  • ExecuteScalar - used to return a single value.

Once a MySqlCommand object has been created, you will call one of the above methods on it to carry out a database operation, such as perform a query. The results are usually returned into a MySqlDataReader object, and then processed, for example the results might be displayed. The following code demonstrates how this could be done.

using System;using System.Data;using MySql.Data;using MySql.Data.MySqlClient;public class Tutorial2{ public static void Main() { string connStr = "server=localhost;user=root;database=world;port=3306;password=******;"; MySqlConnection conn = new MySqlConnection(connStr); try { Console.WriteLine("Connecting to MySQL..."); conn.Open(); string sql = "SELECT Name, HeadOfState FROM Country WHERE Continent='Oceania'"; MySqlCommand cmd = new MySqlCommand(sql, conn); MySqlDataReader rdr = cmd.ExecuteReader(); while (rdr.Read()) { Console.WriteLine(rdr[0]+" -- "+rdr[1]); } rdr.Close(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } conn.Close(); Console.WriteLine("Done."); }}

When a connection has been created and opened, the code then creates a MySqlCommand object. Note that the SQL query to be executed is passed to the MySqlCommand constructor. The ExecuteReader method is then used to generate a MySqlReader object. The MySqlReader object contains the results generated by the SQL executed on the command object. Once the results have been obtained in a MySqlReader object, the results can be processed. In this case, the information is printed out by a while loop. Finally, the MySqlReader object is disposed of by running its Close method on it.

In the next example, you will see how to use the ExecuteNonQuery method.

The procedure for performing an ExecuteNonQuery method call is simpler, as there is no need to create an object to store results. This is because ExecuteNonQuery is only used for inserting, updating and deleting data. The following example illustrates a simple update to the Country table:

using System;using System.Data;using MySql.Data;using MySql.Data.MySqlClient;public class Tutorial3{ public static void Main() { string connStr = "server=localhost;user=root;database=world;port=3306;password=******;"; MySqlConnection conn = new MySqlConnection(connStr); try { Console.WriteLine("Connecting to MySQL..."); conn.Open(); string sql = "INSERT INTO Country (Name, HeadOfState, Continent) VALUES ('Disneyland','Mickey Mouse', 'North America')"; MySqlCommand cmd = new MySqlCommand(sql, conn); cmd.ExecuteNonQuery(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } conn.Close(); Console.WriteLine("Done."); }}

The query is constructed, the command object created and the ExecuteNonQuery method called on the command object. You can access your MySQL database with the mysql command interpreter and verify that the update was carried out correctly.

Finally, you will see how the ExecuteScalar method can be used to return a single value. Again, this is straightforward, as a MySqlDataReader object is not required to store results, a simple variable will do. The following code illustrates how to use ExecuteScalar:

using System;using System.Data;using MySql.Data;using MySql.Data.MySqlClient;public class Tutorial4{ public static void Main() { string connStr = "server=localhost;user=root;database=world;port=3306;password=******;"; MySqlConnection conn = new MySqlConnection(connStr); try { Console.WriteLine("Connecting to MySQL..."); conn.Open(); string sql = "SELECT COUNT(*) FROM Country"; MySqlCommand cmd = new MySqlCommand(sql, conn); object result = cmd.ExecuteScalar(); if (result != null) { int r = Convert.ToInt32(result); Console.WriteLine("Number of countries in the World database is: " + r); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } conn.Close(); Console.WriteLine("Done."); }}

This example uses a simple query to count the rows in the Country table. The result is obtained by calling ExecuteScalar on the command object.

22.2.4.1.3. Working with Decoupled Data

Previously, when using MySqlDataReader, the connection to the database was continually maintained, unless explicitly closed. It is also possible to work in a manner where a connection is only established when needed. For example, in this mode, a connection could be established to read a chunk of data, the data could then be modified by the application as required. A connection could then be reestablished only if and when the application writes data back to the database. This decouples the working data set from the database.

This decoupled mode of working with data is supported by Connector/Net. There are several parts involved in allowing this method to work:

  • Data Set - The Data Set is the area in which data is loaded to read or modify it. A DataSet object is instantiated, which can store multiple tables of data.

  • Data Adapter - The Data Adapter is the interface between the Data Set and the database itself. The Data Adapter is responsible for efficiently managing connections to the database, opening and closing them as required. The Data Adapter is created by instantiating an object of the MySqlDataAdapter class. The MySqlDataAdapter object has two main methods: Fill which reads data into the Data Set, and Update, which writes data from the Data Set to the database.

  • Command Builder - The Command Builder is a support object. The Command Builder works in conjunction with the Data Adapter. When a MySqlDataAdapter object is created, it is typically given an initial SELECT statement. From this SELECT statement the Command Builder can work out the corresponding INSERT, UPDATE and DELETE statements that would be required to update the database. To create the Command Builder, an object of the class MySqlCommandBuilder is created.

Each of these classes will now be discussed in more detail.

Instantiating a DataSet object

A DataSet object can be created simply, as shown in the following example code snippet:

DataSet dsCountry;...dsCountry = new DataSet();

Although this creates the DataSet object, it has not yet filled it with data. For that, a Data Adapter is required.

Instantiating a MySqlDataAdapter object

The MySqlDataAdapter can be created as illustrated by the following example:

MySqlDataAdapter daCountry;...string sql = "SELECT Code, Name, HeadOfState FROM Country WHERE Continent='North America'";daCountry = new MySqlDataAdapter (sql, conn);

Note, the MySqlDataAdapter is given the SQL specifying the data to work with.

Instantiating a MySqlCommandBuilder object

Once the MySqlDataAdapter has been created, it is necessary to generate the additional statements required for inserting, updating and deleting data. There are several ways to do this, but in this tutorial you will see how this can most easily be done with MySqlCommandBuilder. The following code snippet illustrates how this is done:

MySqlCommandBuilder cb = new MySqlCommandBuilder(daCountry);

Note that the MySqlDataAdapter object is passed as a parameter to the command builder.

Filling the Data Set

To do anything useful with the data from your database, you need to load it into a Data Set. This is one of the jobs of the MySqlDataAdapter object, and is carried out with its Fill method. The following example code illustrates this:

DataSet dsCountry;...dsCountry = new DataSet();...daCountry.Fill(dsCountry, "Country");

Note the Fill method is a MySqlDataAdapter method, the Data Adapter knows how to establish a connec tion with the database and retrieve the required data, and then populates the Data Set when the Fill method is called. The second parameter "Country" is the table in the Data Set to update.

Updating the Data Set

The data in the Data Set can now be manipulated by the application as required. At some point, changes to data will need to be written back to the database. This is achieved through a MySqlDataAdapter method, the Update method.

daCountry.Update(dsCountry, "Country");

Again, the Data Set and the table within the Data Set to update are specified.

Working Example

The interactions between the DataSet, MySqlDataAdapter and MySqlCommandBuilder classes can be a little confusing, so their operation can perhaps be best illustrated by working code.

In this example, data from the World database is read into a Data Grid View control. Here, the data can be viewed and changed before clicking an update button. The update button then activates code to write changes back to the database. The code uses the principles explained above. The application was built using the Microsoft Visual Studio to place and create the user interface controls, but the main code that uses the key classes described above is shown below, and is portable.

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using MySql.Data;using MySql.Data.MySqlClient;namespace WindowsFormsApplication5{ public partial class Form1 : Form { MySqlDataAdapter daCountry; DataSet dsCountry; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { string connStr = "server=localhost;user=root;database=world;port=3306;password=******;"; MySqlConnection conn = new MySqlConnection(connStr); try { label2.Text = "Connecting to MySQL..."; string sql = "SELECT Code, Name, HeadOfState FROM Country WHERE Continent='North America'"; daCountry = new MySqlDataAdapter (sql, conn); MySqlCommandBuilder cb = new MySqlCommandBuilder(daCountry); dsCountry = new DataSet(); daCountry.Fill(dsCountry, "Country"); dataGridView1.DataSource = dsCountry; dataGridView1.DataMember = "Country"; } catch (Exception ex) { label2.Text = ex.ToString(); } } private void button1_Click(object sender, EventArgs e) { daCountry.Update(dsCountry, "Country"); label2.Text = "MySQL Database Updated!"; } }}

The application running is shown below:

Figure 22.41. World Database Application

World Database Application

22.2.4.1.4. Working with Parameters

This part of the tutorial shows you how to use parameters in your Connector/Net application.

Although it is possible to build SQL query strings directly from user input, this is not advisable as it does not prevent erroneous or malicious information being entered. It is safer to use parameters as they will be processed as field data only. For example, imagine the following query was constructed from user input:

string sql = "SELECT Name, HeadOfState FROM Country WHERE Continent = "+user_continent;

If the string user_continent came from a Text Box control, there would potentially be no control over the string entered by the user. The user could enter a string that generates a run time error, or in the worst case actually harms the system. When using parameters it is not possible to do this because a parameter is only ever treated as a field parameter, rather than an arbitrary piece of SQL code.

The same query written user a parameter for user input would be:

string sql = "SELECT Name, HeadOfState FROM Country WHERE Continent = @Continent";

Note that the parameter is preceded by an '@' symbol to indicate it is to be treated as a parameter.

As well as marking the position of the parameter in the query string, it is necessary to add a parameter to the Command object. This is illustrated by the following code snippet:

cmd.Parameters.AddWithValue("@Continent", "North America");

In this example the string "North America" is supplied as the parameter value statically, but in a more practical example it would come from a user input control.

A further example illustrates the complete process:

using System;using System.Data;using MySql.Data;using MySql.Data.MySqlClient;public class Tutorial5{ public static void Main() { string connStr = "server=localhost;user=root;database=world;port=3306;password=******;"; MySqlConnection conn = new MySqlConnection(connStr); try { Console.WriteLine("Connecting to MySQL..."); conn.Open(); string sql = "SELECT Name, HeadOfState FROM Country WHERE Continent=@Continent"; MySqlCommand cmd = new MySqlCommand(sql, conn); Console.WriteLine("Enter a continent e.g. 'North America','Europe': "); string user_input = Console.ReadLine(); cmd.Parameters.AddWithValue("@Continent", user_input); MySqlDataReader rdr = cmd.ExecuteReader(); while (rdr.Read()) { Console.WriteLine(rdr["Name"]+" --- "+rdr["HeadOfState"]); } rdr.Close(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } conn.Close(); Console.WriteLine("Done."); }}

In this part of the tutorial you have see how to use parameters to make your code more secure.

22.2.4.1.5. Working with Stored Procedures

This section illustrates how to work with stored procedures. Putting database-intensive operations into stored procedures lets you define an API for your database application. You can reuse this API across multiple applications and multiple programming languages. This technique avoids duplicating database code, saving time and effort when you make updates due to schema changes, tune the performance of queries, or add new database operations for logging, security, and so on. Before working through this tutorial, familiarize yourself with the CREATE PROCEDURE and CREATE FUNCTION statements that create different kinds of stored routines.

For the purposes of this tutorial, you will create a simple stored procedure to see how it can be called from Connector/Net. In the MySQL Client program, connect to the World database and enter the following stored procedure:

DELIMITER //CREATE PROCEDURE country_hos(IN con CHAR(20))BEGIN  SELECT Name, HeadOfState FROM Country  WHERE Continent = con;END //DELIMITER ;

Test that the stored procedure works as expected by typing the following into the mysql command interpreter:

CALL country_hos('Europe');

Note that The stored routine takes a single parameter, which is the continent to restrict your search to.

Having confirmed that the stored procedure is present and correct, you can see how to access it from Connector/Net.

Calling a stored procedure from your Connector/Net application is similar to techniques you have seen earlier in this tutorial. A MySqlCommand object is created, but rather than taking an SQL query as a parameter, it takes the name of the stored procedure to call. Set the MySqlCommand object to the type of stored procedure, as shown by the following code snippet:

string rtn = "country_hos";MySqlCommand cmd = new MySqlCommand(rtn, conn);cmd.CommandType = CommandType.StoredProcedure;

In this case, the stored procedure requires you to pass a parameter. This can be achieved using the techniques seen in the previous section on parameters, Section 22.2.4.1.4, "Working with Parameters", as shown in the following code snippet:

cmd.Parameters.AddWithValue("@con", "Europe");

The value of the parameter @con could more realistically have come from a user input control, but for simplicity it is set as a static string in this example.

At this point, everything is set up and you can call the routine using techniques also learned in earlier sections. In this case, the ExecuteReader method of the MySqlCommand object is used.

Complete working code for the stored procedure example is shown below:

using System;using System.Data;using MySql.Data;using MySql.Data.MySqlClient;public class Tutorial6{ public static void Main() { string connStr = "server=localhost;user=root;database=world;port=3306;password=******;"; MySqlConnection conn = new MySqlConnection(connStr); try { Console.WriteLine("Connecting to MySQL..."); conn.Open(); string rtn = "country_hos"; MySqlCommand cmd = new MySqlCommand(rtn, conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@con", "Europe"); MySqlDataReader rdr = cmd.ExecuteReader(); while (rdr.Read()) { Console.WriteLine(rdr[0] + " --- " + rdr[1]); } rdr.Close(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } conn.Close(); Console.WriteLine("Done."); }}

In this section, you have seen how to call a stored procedure from Connector/Net. For the moment, this concludes our introductory tutorial on programming with Connector/Net.

22.2.4.2. Tutorial: MySQL Connector/Net ASP.NET Membership and Role Provider

Many web sites feature the facility for the user to create a user account. They can then log into the web site and enjoy a personalized experience. This requires that the developer creates database tables to store user information, along with code to gather and process this data. This represents a burden on the developer, and there is the possibility for security issues to creep into the developed code. However, ASP.NET 2.0 introduced the Membership system. This system is designed around the concept of Membership, Profile and Role Providers, which together provide all of the functionality to implement a user system, that previously would have to have been created by the developer from scratch.

Currently, MySQL Connector/Net provides Membership, Role, Profile and Session State Providers.

This tutorial shows you how to set up your ASP.NET web application to use the MySQL Connector/Net Membership and Role Providers. It assumes that you have MySQL Server installed, along with MySQL Connector/Net and Microsoft Visual Studio. This tutorial was tested with MySQL Connector/Net 6.0.4 and Microsoft Visual Studio 2008 Professional Edition. It is recommended you use 6.0.4 or above for this tutorial.

  1. Create a new database in the MySQL Server using the MySQL Command Line Client program (mysql), or other suitable tool. It does not matter what name is used for the database, but record it. You specify it in the connection string constructed later in this tutorial. This database contains the tables, automatically created for you later, used to store data about users and roles.

  2. Create a new ASP.NET Web Site in Visual Studio. If you are not sure how to do this, refer to Section 22.2.4.6, "Tutorial: Databinding in ASP.NET using LINQ on Entities", which demonstrates how to create a simple ASP.NET web site.

  3. Add References to MySql.Data and MySql.Web to the web site project.

  4. Locate the machine.config file on your system, which is the configuration file for the .NET Framework.

  5. Search the machine.config file to find the membership provider MySQLMembershipProvider.

  6. Add the attribute autogenerateschema="true". The appropriate section should now resemble the following (note: for the sake of brevity some information has been excluded):

    <membership> <providers>   <add name="AspNetSqlMembershipProvider"  type="System.Web.Security.SqlMembershipProvider"  ...  connectionStringName="LocalSqlServer"  ... />   <add name="MySQLMembershipProvider"  autogenerateschema="true"  type="MySql.Web.Security.MySQLMembershipProvider, MySql.Web,  Version=6.0.4.0,  Culture=neutral, PublicKeyToken=c5687fc88969c44d"  connectionStringName="LocalMySqlServer"  ... /> </providers></membership>

    Note that the name for the connection string to be used to connect to the server that contains the membership database is LocalMySqlServer.

    The autogenerateschema="true" attribute will cause MySQL Connector/Net to silently create, or upgrade, the schema on the database server, to contain the required tables for storing membership information.

  7. It is now necessary to create the connection string referenced in the previous step. Load the web site's web.config file into Visual Studio.

  8. Locate the section marked <connectionStrings>. Add the following connection string information:

    <connectionStrings>  <remove name="LocalMySqlServer"/>  <add name="LocalMySqlServer"   connectionString="Datasource=localhost;Database=users;uid=root;   pwd=password;"   providerName="MySql.Data.MySqlClient"/></connectionStrings>

    The database specified is the one created in the first step. You could alternatively have used an existing database.

  9. At this point build the solution to ensure no errors are present. This can be done by selecting Build, Build Solution from the main menu, or pressing F6.

  10. ASP.NET supports the concept of locally and remotely authenticated users. With local authentication the user is validated using their Windows credentials when they attempt to access the web site. This can be useful in an Intranet environment. With remote authentication, a user is prompted for their login details when accessing the web site, and these credentials are checked against the membership information stored in a database server such as MySQL Server. You will now see how to choose this form of authentication.

    Start the ASP.NET Web Site Administration Tool. This can be done quickly by clicking the small hammer/Earth icon in the Solution Explorer. You can also launch this tool by selecting Website, ASP.NET Configuration from the main menu.

  11. In the ASP.NET Web Site Administration Tool click the Security tab.

  12. Now click the User Authentication Type link.

  13. Select the From the internet radio button. The web site will now need to provide a form to allow the user to enter their login details. These will be checked against membership information stored in the MySQL database.

    Figure 22.42. Authentication Type

    Authentication Type

  14. You now need to specify the Role and Membership Provider to be used. Click the Provider tab.

  15. Click the Select a different provider for each feature (advanced) link.

  16. Now select the MySQLMembershipProvider and the MySQLRoleProvider radio buttons.

    Figure 22.43. Select Membership and Role Provider

    Select Membership and Role Provider

  17. In Visual Studio, rebuild the solution by selecting Build, Rebuild Solution from the main menu.

  18. Check that the necessary schema has been created. This can be achieved using the mysql command interpreter.

    Figure 22.44. Membership and Role Provider Tables

    Membership and Role Provider Tables

  19. Assuming all is present and correct, you can now create users and roles for your web application. The easiest way to do this is with the ASP.NET Web Site Administration Tool. However, many web applications contain their own modules for creating roles and users. For simplicity, the ASP.NET Web Site Administration Tool will be used in this tutorial.

  20. In the ASP.NET Web Site Administration Tool, click the Security tab. Now that both the Membership and Role Provider are enabled, you will see links for creating roles and users. Click the Create or Manage Roles link.

    Figure 22.45. Security Tab

    Security Tab

  21. You can now enter the name of a new Role and click Add Role to create the new Role. Create new Roles as required.

  22. Click the Back button.

  23. Click the Create User link. You can now fill in information about the user to be created, and also allocate that user to one or more Roles.

    Figure 22.46. Create User

    Create User

  24. Using the mysql command interpreter, you can check that your database has been correctly populated with the Membership and Role data.

    Figure 22.47. Membership and Roles Table Contents

    Membership and Roles Table Contents

In this tutorial, you have seen how to set up the MySQL Connector/Net Membership and Role Providers for use in your ASP.NET web application.

22.2.4.3. Tutorial: MySQL Connector/Net ASP.NET Session State Provider

MySQL Connector/Net from version 6.1 has included a MySQL Session State Provider. This provider enables you to store session state in a MySQL database. The following tutorial shows you how to prepare to use the MySQL Session State Provider, and then store session data into the MySQL database. This tutorial uses Microsoft Visual Studio 2008 Professional Edition, MySQL Connector/Net 6.1.1 and MySQL Server 5.1. This tutorial also assumes you have created an empty database, for example test, where you will store session data. You could do this using the mysql command interpreter.

  1. In Visual Studio, create a new ASP.NET web site. If you are not sure how to do this, refer to the tutorial Section 22.2.4.6, "Tutorial: Databinding in ASP.NET using LINQ on Entities", which demonstrates how to do this.

  2. Launch the MySQL MySQL Website Configuration tool. Due to a bug in 6.1.1, this may not appear unless you are connected to a server in the Server Explorer. If you are unfamiliar with the MySQL Website Configuration tool, consider first working through the tutorial in Section 22.2.3.12, "MySQL Website Configuration Tool".

  3. Navigate through the wizard to the Session State page. Make sure the check box Use MySQL to manage my ASP.NET session data is selected.

  4. On the same page, configure the connection string to the database that will contain your session data. If this database is empty, MySQL Connector/Net will create the schema required to store session data.

  5. Ensure that the check box Autogenerate Schema is selected so that MySQL Connector/Net will create the schema in your database to store the session data correctly.

  6. Enter the name of your application.

  7. Click Finish. The MySQL Website Configuration tool will now update your application's web.config file with information about the connection string and default providers to be used. In this case, we have selected the MySQL Session State Provider.

At this point, you are ready to use the MySQL database to store session data. To test that the set up has worked, you can write a simple program that uses session variables.

  1. Open Default.aspx.cs. In the Page_Load method, add the following code:

    Session["SessionVariable1"] = "Test string";
  2. Build your solution.

  3. Run the solution (without debugging). When the application runs, the provider will autogenerate tables required in the database you chose when setting up the application.

  4. Check that the schema was in fact created. Using the MySQL Command Line Client use the target database and then type SHOW TABLES;. You will see that MySQL Connector/Net has created the required schema automatically, as we selected this to happen in the MySQL Website Configuration tool.

  5. Now view the contents of these tables by typing SELECT * FROM my_aspnet_sessions; in the mysql command interpreter. This will display the session data our application used. Note that this is stored in binary format so some data may not display as expected.

At this point, you have installed the Session State Provider and carried out a preliminary test of the installation. You will now work a bit more with the Session State Provider.

In this part of the tutorial, you will set and retrieve a session variable. You can work with your existing project.

  1. Select the Default.aspx and switch to Design View. Add a text box and three buttons. Change the text property for the buttons to "Store Session Variable", "Clear Textbox", and "Show Session Variable". These will be Button1, Button2 and Button3 respectively. Build your solution to ensure that no errors have been introduced.

  2. Still in the Design View, double-click Button1. Now to the Button1_Click event handler add code some the handler resembles the following:

    protected void Button1_Click(object sender, EventArgs e){ Session["SessionString"] = TextBox1.Text;}

    You have created a new Session variable accessed using the key "SessionString". This will be set to the text that was entered into the text box when Button1 is clicked.

  3. In Design View, double-click Button2 to add its click event handler. This button needs to clear text from the text box. The code to do this is as follows:

    protected void Button2_Click(object sender, EventArgs e){ TextBox1.Text = "";}

    The code simply assigns an empty string to the Text property of the text box.

  4. In the Design View double-click Button3 and modify the click handler as follows:

    protected void Button3_Click(object sender, EventArgs e){ TextBox1.Text = (String)Session["SessionString"];}

    This will retrieve the session string and display it in the text box.

  5. Now modify the Page_Load method as follows:

    protected void Page_Load(object sender, EventArgs e){ if (!IsPostBack) {   TextBox1.Text = "Enter some text"; }}

    This ensures that when the page loads the text box Text property is reset.

  6. Ensure that the solution is saved and then rebuild the solution.

  7. Run the solution without debugging.

  8. The form will be displayed. Enter some text into the text box. Now click Store Session Variable. At this point you have stored the string in a session variable.

  9. Now click Clear Text to clear the text box.

  10. Now click Show Session Variable to retrieve and display the session variable.

  11. Refresh the page to destroy the form and display a new form.

  12. Click Show Session Variable the text box will display the stored session variable, demonstrating that the refreshing the page does not destroy the session variable.

This illustrates that the session state data is not destroyed when a page is reloaded.

22.2.4.4. Tutorial: MySQL Connector/Net ASP.NET Profile Provider

This tutorial shows you how to use the MySQL Profile Provider to store user profile information in a MySQL database. The tutorial uses MySQL Connector/Net 6.1.1, MySQL Server 5.1 and Microsoft Visual Studio 2008 Professional Edition.

Many modern web sites allow the user to create a personal profile. This requires a significant amount of code, but ASP.NET reduces this considerable by including the functionality in its Profile classes. The Profile Provider provides an abstraction between these classes and a data source. The MySQL Profile Provider enables profile data to be stored in a MySQL database. This enables the profile properties to be written to a persistent store, and be retrieved when required. The Profile Provider also enables profile data to be managed effectively, for example it enables profiles that have not been accessed since a specific date to be deleted.

The following steps show you how you can select the MySQL Profile Provider.

  1. Create a new ASP.NET web project.

  2. Select the MySQL Website Configuration tool. Due to a bug in 6.1.1 you may have to first connect to a server in Server Explorer before the tool's icon will display in the toolbar of the Solution Explorer.

  3. In the MySQL Website Configuration tool navigate through the tool to the Profiles page.

  4. Select the Use MySQL to manage my profiles check box.

  5. Select the Autogenerate Schema check box.

  6. Click the Edit... button and configure a connection string for the database that will be used to store user profile information.

  7. Navigate to the last page of the tool and click Finish to save your changes and exit the tool.

At this point you are now ready to start using the MySQL Profile Provider. With the following steps you can carry out a preliminary test of your installation.

  1. Open your web.config file.

  2. Add a simple profile such as the following:

    <system.web>  <anonymousIdentification enabled="true"/>   <profile defaultProvider="MySQLProfileProvider"> ... <properties>  <add name="Name" allowAnonymous="true"/>  <add name="Age" allowAnonymous="true" type="System.UInt16"/>  <group name="UI"> <add name="Color" allowAnonymous="true" defaultValue="Blue"/> <add name="Style" allowAnonymous="true" defaultValue="Plain"/>  </group> </properties>  </profile>  ...

    Note that anonymousIdentification has been set to true. This enables users who have not been authenticated to use profiles. They are identified by a GUID in a cookie rather than by user name.

Now that the simple profile has been defined in web.config, the next step is to write some code to test the profile.

  1. In Design View design a simple page with the following controls:

    Figure 22.48. Simple Profile Application

    Simple Profile Application

    These will allow the user to enter some profile information. The user can also use the buttons to save their profile, clear the page, and restore their profile data.

  2. In the Code View add code as follows:

    ...protected void Page_Load(object sender, EventArgs e){ if (!IsPostBack) { TextBox1.Text = Profile.Name; TextBox2.Text = Profile.Age.ToString(); Label1.Text = Profile.UI.Color; }} // Store Profileprotected void Button1_Click(object sender, EventArgs e){ Profile.Name = TextBox1.Text; Profile.Age = UInt16.Parse(TextBox2.Text);} // Clear Formprotected void Button2_Click(object sender, EventArgs e){ TextBox1.Text = ""; TextBox2.Text = ""; Label1.Text = "";}// Retrieve Profileprotected void Button3_Click(object sender, EventArgs e){ TextBox1.Text = Profile.Name; TextBox2.Text = Profile.Age.ToString(); Label1.Text = Profile.UI.Color;}protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e){ Profile.UI.Color = DropDownList1.SelectedValue;}...
  3. Save all files and build the solution to check that no errors have been introduced.

  4. Run the application.

  5. Enter your name, age and select a color from the listbox. Now store this information in your profile by clicking Store Profile. Note that if you do not select a color from the listbox your profile will use the default color Blue that was specified in the web.config file.

  6. Click Clear Form to clear text from the textboxes and the label that displays your chosen color.

  7. Now click Retrieve Profile to restore your profile data from the MySQL database.

  8. Now exit the browser to terminate the application.

  9. Run the application again. Note that when the page loads your profile information is restored from the MySQL database.

In this tutorial you have seen how to using the MySQL Profile Provider with MySQL Connector/Net.

22.2.4.5. Tutorial: Using an Entity Framework Entity as a Windows Forms DataSource

In this tutorial you will learn how to create a Windows Forms Data Source from an Entity in an Entity Data Model. This tutorial assumes that you have installed the World example database, which can be downloaded from the MySQL Documentation page. You can also find details on how to install the database on the same page. It will also be convenient for you to create a connection to the World database after it is installed. For instructions on how to do this see Section 22.2.3.1, "Making a Connection".

Creating a new Windows Forms application

The first step is to create a new Windows Forms application.

  1. In Visual Studio, select File, New, Project from the main menu.

  2. Choose the Windows Forms Application installed template. Click OK. The solution is created.

Adding an Entity Data Model

You will now add an Entity Data Model to your solution.

  1. In the Solution Explorer, right-click your application and select Add, New Item.... From Visual Studio installed templates select ADO.NET Entity Data Model. Click Add.

    Figure 22.49. Add Entity Data Model

    Add Entity Data Model

  2. You will now see the Entity Data Model Wizard. You will use the wizard to generate the Entity Data Model from the world example database. Select the icon Generate from database. Click Next.

    Figure 22.50. Entity Data Model Wizard Screen 1

    Entity Data Model Wizard Screen 1

  3. You can now select the connection you made earlier to the World database. If you have not already done so, you can create the new connection at this time by clicking New Connection.... For further instructions on creating a connection to a database see Section 22.2.3.1, "Making a Connection".

    Figure 22.51. Entity Data Model Wizard Screen 2

    Entity Data Model Wizard Screen 2

  4. Make a note of the entity connection settings to be used in App.Config, as these will be used later to write the necessary control code.

  5. Click Next.

  6. The Entity Data Model Wizard connects to the database. You are then presented with a tree structure of the database. From this you can select the object you would like to include in your model. If you had created Views and Stored Routines these will be displayed along with any tables. In this example you just need to select the tables. Click Finish to create the model and exit the wizard.

    Figure 22.52. Entity Data Model Wizard Screen 3

    Entity Data Model Wizard Screen 3

  7. Visual Studio will generate the model and then display it.

    Figure 22.53. Entity Data Model Diagram

    Entity Data Model Diagram

  8. From the Visual Studio main menu select Build, Build Solution, to ensure that everything compiles correctly so far.

Adding a new Data Source

You will now add a new Data Source to your project and see how it can be used to read and write to the database.

  1. From the Visual Studio main menu select Data, Add New Data Source.... You will be presented with the Data Source Configuration Wizard.

    Figure 22.54. Entity Data Source Configuration Wizard Screen 1

    Entity Data Source Configuration Wizard Screen 1

  2. Select the Object icon. Click Next.

  3. You will now select the Object to bind to. Expand the tree. In this tutorial, you will select the city table. Once the city table has been selected click Next.

    Figure 22.55. Entity Data Source Configuration Wizard Screen 2

    Entity Data Source Configuration Wizard Screen 2

  4. The wizard will confirm that the city object is to be added. Click Finish.

    Figure 22.56. Entity Data Source Configuration Wizard Screen 3

    Entity Data Source Configuration Wizard Screen 3

  5. The city object will be display in the Data Sources panel. If the Data Sources panel is not displayed, select Data, Show Data Sources from the Visual Studio main menu. The docked panel will then be displayed.

    Figure 22.57. Data Sources

    Data Sources

Using the Data Source in a Windows Form

You will now learn how to use the Data Source in a Windows Form.

  1. In the Data Sources panel select the Data Source you just created and drag and drop it onto the Form Designer. By default the Data Source object will be added as a Data Grid View control. Note that the Data Grid View control is bound to the cityBindingSource and the Navigator control is bound to cityBindingNavigator.

    Figure 22.58. Data Form Designer


  2. Save and rebuild the solution before continuing.

Adding Code to Populate the Data Grid View

You are now ready to add code to ensure that the Data Grid View control will be populated with data from the City database table.

  1. Double-click the form to access its code.

  2. Add code to instantiate the Entity Data Model's EntityContainer object and retrieve data from the database to populate the control.

    Figure 22.59. Adding Code to the Form


  3. Save and rebuild the solution.

  4. Run the solution. Ensure the grid is populated and you can navigate the database.

    Figure 22.60. The Populated Grid Control

    The Populated Grid Control

Adding Code to Save Changes to the Database

You will now add code to enable you to save changes to the database.

The Binding source component ensures that changes made in the Data Grid View control are also made to the Entity classes bound to it. However, that data needs to be saved back from the entities to the database itself. This can be achieved by the enabling of the Save button in the Navigator control, and the addition of some code.

  1. In the Form Designer, click the Save icon in the Form toolbar and ensure that its Enabled property is set to True.

    Figure 22.61. Save Button Enabled


  2. Double-click the Save icon in the Form toolbar to display its code.

  3. You now need to add code to ensure that data is saved to the database when the save button is clicked in the application.

    Figure 22.62. Adding Save Code to the Form

    Adding Save Code to the Form

  4. Once the code has been added, save the solution and rebuild it. Run the application and verify that changes made in the grid are saved.

22.2.4.6. Tutorial: Databinding in ASP.NET using LINQ on Entities

In this tutorial you create an ASP.NET web page that binds LINQ queries to entities using the Entity Framework mapping.

If you have not already done so, install the World example database prior to attempting this tutorial. See the tutorial Section 22.2.4.5, "Tutorial: Using an Entity Framework Entity as a Windows Forms Data Source" for instructions on downloading and installing this database.

Creating an ASP.NET web site

In this part of the tutorial, you create an ASP.NET web site. The web site uses the World database. The main web page features a drop down list from which you can select a country. Data about that country's cities is then displayed in a grid view control.

  1. From the Visual Studio main menu select File, New, Web Site....

  2. From the Visual Studio installed templates select ASP.NET Web Site. Click OK. You will be presented with the Source view of your web page by default.

  3. Click the Design view tab situated underneath the Source view panel.

    Figure 22.63. The Design Tab

    The Design Tab

  4. In the Design view panel, enter some text to decorate the blank web page.

  5. Click Toolbox. From the list of controls select DropDownList. Drag and drop the control to a location beneath the text on your web page.

    Figure 22.64. Drop Down List

    Drop Down List

  6. From the DropDownList control's context menu, ensure that the Enable AutoPostBack check box is enabled. This will ensure the control's event handler is called when an item is selected. The user's choice will in turn be used to populate the GridView control.

    Figure 22.65. Enable AutoPostBack

    Enable AutoPostBack

  7. From the Toolbox select the GridView control.

    Figure 22.66. Grid View Control

    Grid Vew Control

    Drag and drop the Grid Vew control to a location just below the Drop Down List you already placed.

    Figure 22.67. Placed Grid Vew Control


  8. At this point it is recommended that you save your solution, and build the solution to ensure that there are no errors.

  9. If you run the solution you will see that the text and drop down list are displayed, but the list is empty. Also, the grid view does not appear at all. Adding this functionality is described in the following sections.

At this stage you have a web site that will build, but further functionality is required. The next step will be to use the Entity Framework to create a mapping from the World database into entities that you can control programmatically.

Creating an ADO.NET Entity Data Model

In this stage of the tutorial you will add an ADO.NET Entity Data Model to your project, using the World database at the storage level. The procedure for doing this is described in the tutorial Section 22.2.4.5, "Tutorial: Using an Entity Framework Entity as a Windows Forms Data Source", and so will not be repeated here.

Populating a Drop Data List Box with using the results of a entity LINQ query

In this part of the tutorial you will write code to populate the DropDownList control. When the web page loads the data to populate the list will be achieved by using the results of a LINQ query on the model created previously.

  1. In the Design view panel, double-click any blank area. This brings up the Page_Load method.

  2. Modify the relevant section of code according to the following listing:

    ...public partial class _Default : System.Web.UI.Page{ worldModel.worldEntities we; protected void Page_Load(object sender, EventArgs e) { we = new worldModel.worldEntities(); if (!IsPostBack) { var countryQuery = from c in we.country   orderby c.Name   select new { c.Code, c.Name }; DropDownList1.DataValueField = "Code"; DropDownList1.DataTextField = "Name"; DropDownList1.DataSource = countryQuery; DataBind(); } }...

    Note that the list control only needs to be populated when the page first loads. The conditional code ensures that if the page is subsequently reloaded, the list control is not repopulated, which would cause the user selection to be lost.

  3. Save the solution, build it and run it. You should see the list control has been populated. You can select an item, but as yet the grid view control does not appear.

At this point you have a working Drop Down List control, populated by a LINQ query on your entity data model.

Populating a Grid View control using an entity LINQ query

In the last part of this tutorial you will populate the Grid View Control using a LINQ query on your entity data model.

  1. In the Design view, double-click the DropDownList control. This causes its SelectedIndexChanged code to be displayed. This method is called when a user selects an item in the list control and thus fires an AutoPostBack event.

  2. Modify the relevant section of code accordingly to the following listing:

    ... protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) { var cityQuery = from c in we.city where c.CountryCode == DropDownList1.SelectedValue orderby c.Name select new { c.Name, c.Population, c.CountryCode }; GridView1.DataSource = cityQuery; DataBind(); }...

    The grid view control is populated from the result of the LINQ query on the entity data model.

  3. As a check compare your code to that shown in the following screenshot:

    Figure 22.68. Source Code

    Source Code

  4. Save, build and run the solution. As you select a country you will see its cities are displayed in the grid view control.

    Figure 22.69. The Working Web Site

    The Working Web Site

In this tutorial you have seen how to create an ASP.NET web site, you have also seen how you can access a MySQL database using LINQ queries on an entity data model.

22.2.4.7. Tutorial: Using SSL with MySQL Connector/Net

In this tutorial you will learn how you can use MySQL Connector/Net to connect to a MySQL server configured to use SSL. Support for SSL client certificates was added with MySQL Connector/Net 6.2.

MySQL Server uses the PEM format for certificates and private keys. This tutorial will use the test certificates from the server test suite by way of example. You can obtain the MySQL Server source code from MySQL Downloads. The certificates can be found in the directory ./mysql-test/std_data.

To carry out the steps in this tutorial, you must have Open SSL installed. This can be downloaded for Microsoft Windows at no charge from Shining Light Productions.

Further details on the connection string options used in this tutorial can be found at Section 22.2.6, "Connector/Net Connection String Options Reference".

Configuring the MySQL Server to use SSL

  1. In the MySQL Server configuration file, set the SSL parameters as follows:

    ssl-ca=path/to/repo/mysql-test/std_data/cacert.pem ssl-cert=path/to/repo/mysql-test/std_data/server-cert.pem ssl-key=path/to/repo/mysql-test/std_data/server-key.pem 

    Adjust the directories according to the location in which you installed the MySQL source code.

  2. In this step you create a test user and set the user to require SSL.

    Using the MySQL Command Line Client, connect as root and create the user sslclient.

  3. To set privileges and requirements, issue the following command:

    GRANT ALL PRIVILEGES ON *.* TO sslclient@'%' REQUIRE SSL;

Creating a certificate file to use with the .NET client

  1. The .NET client does not use the PEM file format, as .NET does not support this format natively. You will be using test client certificates from the same server repository, for the purposes of this example. Convert these to PFX format first. This format is also known as PKCS#12. An article describing this procedure can be found at the Citrix website. From the directory server-repository-root/mysql-test/std_data, issue the following command:

    openssl pkcs12 -export -in client-cert.pem -inkey client-key.pem -certfile cacert.pem -out client.pfx
  2. When asked for an export password, enter the password "pass". The file client.pfx will be generated. This file is used in the remainder of the tutorial.

Connecting to the server using a file-based certificate

  1. You will use PFX file, client.pfx you created in the previous step to authenticate the client. The following example demonstrates how to connect using the SSL Mode, CertificateFile and CertificatePassword connection string options:

    using (MySqlConnection connection = new MySqlConnection(   "database=test;user=sslclient;" + "CertificateFile=H:\\bzr\\mysql-trunk\\mysql-test\\std_data\\client.pfx" + "CertificatePassword=pass;" +   "SSL Mode=Required ")) { connection.Open(); }

    The path to the certificate file will need to be changed to reflect your individual installation.

Connecting to the server using a store-based certificate

  1. The first step is to import the PFX file, client.pfx, into the Personal Store. Double-click the file in Windows explorer. This launches the Certificate Import Wizard.

  2. Follow the steps dictated by the wizard, and when prompted for the password for the PFX file, enter "pass".

  3. Click Finish to close the wizard and import the certificate into the personal store.

Examine certificates in the Personal Store

  1. Start the Microsoft Management Console by entering mmc.exe at a command prompt.

  2. Select File, Add/Remove snap-in. Click Add. Select Certificates from the list of available snap-ins in the dialog.

  3. Click Add button in the dialog, and select the My user account radio button. This is used for personal certificates.

  4. Click the Finish button.

  5. Click OK to close the Add/Remove Snap-in dialog.

  6. You will now have Certificates � Current User displayed in the left panel of the Microsoft Management Console. Expand the Certificates - Current User tree item and select Personal, Certificates. The right-hand panel will display a certificate issued to MySQL. This is the certificate that was previously imported. Double-click the certificate to display its details.

  7. After you have imported the certificate to the Personal Store, you can use a more succint connection string to connect to the database, as illustrated by the following code:

    using (MySqlConnection connection = new MySqlConnection( "database=test;user=sslclient;" + "Certificate Store Location=CurrentUser;" + "SSL Mode=Required")) { connection.Open(); }

Certificate Thumbprint Parameter

If you have a large number of certificates in your store, and many have the same Issuer, this can be a source of confusion and result in the wrong certificate being used. To alleviate this situation, there is an optional Certificate Thumbprint parameter that can additionally be specified as part of the connection string. As mentioned before, you can double-click a certificate in the Microsoft Management Console to display the certificate's details. When the Certificate dialog is displayed click the Details tab and scroll down to see the thumbprint. The thumbprint will typically be a number such as 47 94 36 00 9a 40 f3 01 7a 14 5c f8 47 9e 76 94 d7 aa de f0. This thumbprint can be used in the connection string, as the following code illustrates:

using (MySqlConnection connection = new MySqlConnection(   "database=test;user=sslclient;" +   "Certificate Store Location=CurrentUser;" +   "Certificate Thumbprint=479436009a40f3017a145cf8479e7694d7aadef0;"+   "SSL Mode=Required")) { connection.Open(); }

Spaces in the thumbprint parameter are optional and the value is case-insensitive.

22.2.4.8. Tutorial: Using MySqlScript

This tutorial teaches you how to use the MySqlScript class. This class enables you to execute a series of statements. Depending on the circumstances, this can be more convenient than using the MySqlCommand approach.

Further details of the MySqlScript class can be found in the reference documentation supplied with MySQL Connector/Net.

To run the example programs in this tutorial, set up a simple test database and table using the mysql Command Line Client or MySQL Workbench. Commands for the mysql Command Line Client are given here:

CREATE DATABASE TestDB;USE TestDB;CREATE TABLE TestTable (id INT NOT NULL PRIMARY KEY  AUTO_INCREMENT, name VARCHAR(100));

The main method of the MySqlScript class is the Execute method. This method causes the script (sequence of statements) assigned to the Query property of the MySqlScript object to be executed. Note the Query property can be set through the MySqlScript constructor or using the Query property. Execute returns the number of statements executed.

The MySqlScript object will execute the specified script on the connection set using the Connection property. Again, this property can be set directly or through the MySqlScript constructor. The following code snippets illustrate this:

string sql = "SELECT * FROM TestTable";...MySqlScript script = new MySqlScript(conn, sql);...MySqlScript script = new MySqlScript();script.Query = sql;script.Connection = conn;...script.Execute();

The MySqlScript class has several events associated with it. There are:

  1. Error - generated if an error occurs.

  2. ScriptCompleted - generated when the script successfully completes execution.

  3. StatementExecuted - generated after each statement is executed.

It is possible to assign event handlers to each of these events. These user-provided routines are called back when the connected event occurs. The following code shows how the event handlers are set up.

script.Error += new MySqlScriptErrorEventHandler(script_Error);script.ScriptCompleted += new EventHandler(script_ScriptCompleted);script.StatementExecuted += new MySqlStatementExecutedEventHandler(script_StatementExecuted);

In VisualStudio, you can save typing by using tab completion to fill out stub routines. Start by typing, for example, "script.Error +=". Then press TAB, and then press TAB again. The assignment is completed, and a stub event handler created. A complete working example is shown below:

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Data;using MySql.Data;using MySql.Data.MySqlClient;namespace MySqlScriptTest{ class Program { static void Main(string[] args) { string connStr = "server=localhost;user=root;database=TestDB;port=3306;password=******;"; MySqlConnection conn = new MySqlConnection(connStr); try { Console.WriteLine("Connecting to MySQL..."); conn.Open(); string sql = "INSERT INTO TestTable(name) VALUES ('Superman');" + "INSERT INTO TestTable(name) VALUES ('Batman');" + "INSERT INTO TestTable(name) VALUES ('Wolverine');" + "INSERT INTO TestTable(name) VALUES ('Storm');"; MySqlScript script = new MySqlScript(conn, sql); script.Error += new MySqlScriptErrorEventHandler(script_Error); script.ScriptCompleted += new EventHandler(script_ScriptCompleted); script.StatementExecuted += new MySqlStatementExecutedEventHandler(script_StatementExecuted); int count = script.Execute(); Console.WriteLine("Executed " + count + " statement(s)."); Console.WriteLine("Delimiter: " + script.Delimiter); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } conn.Close(); Console.WriteLine("Done."); } static void script_StatementExecuted(object sender, MySqlScriptEventArgs args) { Console.WriteLine("script_StatementExecuted"); } static void script_ScriptCompleted(object sender, EventArgs e) { /// EventArgs e will be EventArgs.Empty for this method Console.WriteLine("script_ScriptCompleted!"); } static void script_Error(Object sender, MySqlScriptErrorEventArgs args) { Console.WriteLine("script_Error: " + args.Exception.ToString()); } }}

Note that in the script_ScriptCompleted event handler, the EventArgs parameter e will be EventArgs.Empty. In the case of the ScriptCompleted event there is no additional data to be obtained, which is why the event object is EventArgs.Empty.

22.2.4.8.1. Using Delimiters with MySqlScript

Depending on the nature of the script, you may need control of the delimiter used to separate the statements that will make up a script. The most common example of this is where you have a multi-statement stored routine as part of your script. In this case if the default delimiter of ";" is used you will get an error when you attempt to execute the script. For example, consider the following stored routine:

CREATE PROCEDURE test_routine() BEGIN SELECT name FROM TestTable ORDER BY name; SELECT COUNT(name) FROM TestTable;END

This routine actually needs to be executed on the MySQL Server as a single statement. However, with the default delimiter of ";", the MySqlScript class would interpret the above as two statements, the first being:

CREATE PROCEDURE test_routine() BEGIN SELECT name FROM TestTable ORDER BY name;

Executing this as a statement would generate an error. To solve this problem MySqlScript supports the ability to set a different delimiter. This is achieved through the Delimiter property. For example, you could set the delimiter to "??", in which case the above stored routine would no longer generate an error when executed. Multiple statements can be delimited in the script, so for example, you could have a three statement script such as:

string sql = "DROP PROCEDURE IF EXISTS test_routine??" + "CREATE PROCEDURE test_routine() " +  "BEGIN " +  "SELECT name FROM TestTable ORDER BY name;" +  "SELECT COUNT(name) FROM TestTable;" + "END??" + "CALL test_routine()";

You can change the delimiter back at any point by setting the Delimiter property. The following code shows a complete working example:

using System;using System.Collections.Generic;using System.Linq;using System.Text;using MySql.Data;using MySql.Data.MySqlClient;namespace ConsoleApplication8{ class Program { static void Main(string[] args) { string connStr = "server=localhost;user=root;database=TestDB;port=3306;password=******;"; MySqlConnection conn = new MySqlConnection(connStr); try { Console.WriteLine("Connecting to MySQL..."); conn.Open(); string sql = "DROP PROCEDURE IF EXISTS test_routine??" + "CREATE PROCEDURE test_routine() " + "BEGIN " + "SELECT name FROM TestTable ORDER BY name;" + "SELECT COUNT(name) FROM TestTable;" + "END??" + "CALL test_routine()"; MySqlScript script = new MySqlScript(conn); script.Query = sql; script.Delimiter = "??"; int count = script.Execute(); Console.WriteLine("Executed " + count + " statement(s)"); script.Delimiter = ";"; Console.WriteLine("Delimiter: " + script.Delimiter); Console.WriteLine("Query: " + script.Query); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } conn.Close(); Console.WriteLine("Done."); } }}

22.2.4.9. Tutorial: Generating MySQL DDL from an Entity Framework Model

In this tutorial, you will learn how to create MySQL DDL from an Entity Framework model. Use Visual Studio 2010 and MySQL Connector/Net 6.3 to carry out this tutorial.

  1. Create a new console application in Visual Studio 2010.

  2. Using the Solution Explorer, add a reference to MySql.Data.Entity.

  3. From the Solution Explorer select Add, New Item. In the Add New Item dialog select Online Templates. Select ADO.NET Entity Data Model and click Add. The Entity Data Model dialog will be displayed.

  4. In the Entity Data Model dialog select Empty Model. Click Finish. A blank model will be created.

  5. Create a simple model. A single Entity will do for the purposes of this tutorial.

  6. In the Properties panel select ConceptualEntityModel from the drop-down listbox.

  7. In the Properties panel, locate the DDL Generation Template in the category Database Script Generation.

  8. For the DDL Generation property select SSDLToMySQL.tt(VS) from the drop-down listbox.

  9. Save the solution.

  10. Right-click an empty space in the model design area. The context-sensitive menu will be displayed.

  11. From the context-sensitive menu select Generate Database from Model. The Generate Database Wizard dialog will be displayed.

  12. In the Generate Database Wizard dialog select an existing connection, or create a new connection to a server. Select an appropriate radio button to show or hide sensitive data. For the purposes of this tutorial you can select Yes (although you might skip this for commercial applications).

  13. Click Next. MySQL compatible DDL code will be generated. Click Finish to exit the wizard.

You have seen how to create MySQL DDL code from an Entity Framework model.

Copyright © 1997, 2013, Oracle and/or its affiliates. All rights reserved. Legal Notices
(Sebelumnya) 22. Connectors and APIs22.2.5. Connector/Net Programming (Berikutnya)