![]() |
![]() Alden Hosting provides professional, efficient, and reliable business-class Web hosting services to small- and medium-sized businesses. |
|
|
Secure FTP (sFTP) HostingAlden Hosting offers Secure FTP (sFTP) on our WEB 5 PLAN and our WEB 6 PLAN . At Alden Hosting we eat and breathe Secure FTP (sFTP)! We are the industry leader in providing affordable, quality and efficient Secure FTP (sFTP) hosting in the shared hosting marketplace. Table of Contents This chapter describes MySQL Connectors, drivers that provide connectivity to the MySQL server for client programs. There are currently five MySQL Connectors:
For information on connecting to a MySQL server using other languages and interfaces than those detailed above, including Perl, Python and PHP for other platforms and environments, please refer to the Chapter 22, APIs and Libraries chapter. The MySQL Connector/ODBC is the name for the family of MySQL ODBC drivers (previously called MyODBC drivers) that provide access to a MySQL database using the industry standard Open Database Connectivity (ODBC) API. This reference covers Connector/ODBC 3.51, a version of the API that provides ODBC 3.5x compliant access to a MySQL database. The manual for versions of Connector/ODBC older than 3.51 can be located in the corresponding binary or source distribution. For more information on the ODBC API standard and how to use it, refer to http://www.microsoft.com/data/. The application development part of this reference assumes a good working knowledge of C, general DBMS knowledge, and finally, but not least, familiarity with MySQL. For more information about MySQL functionality and its syntax, refer to http://dev.mysql.com/doc/. Typically, you need to install Connector/ODBC only on Windows machines. For Unix and Mac OS X you can use the native MySQL network or named pipe to communicate with your MySQL database. You may need Connector/ODBC for Unix or Mac OS X if you have an application that requires an ODBC interface to communicate with the database. Applications that require ODBC to communicate with MySQL include ColdFusion, Microsoft Office, and Filemaker Pro. If you want to install the Connector/ODBC connector on a Unix host, then you must also install an ODBC manager. Key topics:
ODBC (Open Database Connectivity) provides a way for client programs to access a wide range of databases or data sources. ODBC is a standardized API that allows connections to SQL database servers. It was developed according to the specifications of the SQL Access Group and defines a set of function calls, error codes, and data types that can be used to develop database-independent applications. ODBC usually is used when database independence or simultaneous access to different data sources is required. For more information about ODBC, refer to http://www.microsoft.com/data/. There are currently two version of Connector/ODBC available:
NoteFrom this section onward, the primary focus of this guide is the Connector/ODBC 3.51 driver. More information about the MyODBC 2.50 driver in the documentation included in the installation packages for that version. If there is a specific issue (error or known problem) that only affects the 2.50 version, it may be included here for reference. NoteVersion numbers for MySQL products are formatted as X.X.X. However, Windows tools (Control Panel, properties display) may show the version numbers as XX.XX.XX. 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. Open Database Connectivity (ODBC) is a widely accepted application-programming interface (API) for database access. It is based on the Call-Level Interface (CLI) specifications from X/Open and ISO/IEC for database APIs and uses Structured Query Language (SQL) as its database access language. A survey of ODBC functions supported by Connector/ODBC is given at Section 23.1.5.1, “Connector/ODBC API Reference”. For general information about ODBC, see http://www.microsoft.com/data/. The Connector/ODBC architecture is based on five components, as shown in the following diagram: ![]()
An ODBC Driver Manager is a library that manages communication between the ODBC-aware application and any drivers. Its main functionality includes:
Both Windows and Mac OS X include ODBC driver managers with the operating system. Most ODBC Driver Manager implementations also include an administration application that makes the configuration of DSN and drivers easier. Examples and information on these managers, including Unix ODBC driver managers are listed below:
You can install the Connector/ODBC drivers using two different methods, a binary installation and a source installation. The binary installation is the easiest and most straightforward method of installation. Using the source installation methods should only be necessary on platforms where a binary installation package is not available, or in situations where you want to customize or modify the installation process or Connector/ODBC drivers before installation. MySQL AB distributes all its products under the General Public License (GPL). You can get a copy of the latest version of Connector/ODBC binaries and sources from the MySQL AB Web site http://dev.mysql.com/downloads/. For more information about Connector/ODBC, visit http://www.mysql.com/products/myodbc/. For more information about licensing, visit http://www.mysql.com/company/legal/licensing/. Connector/ODBC can be used on all major platforms supported by MySQL. You can install it on:
If a binary distribution is not available for a particular
platform, see Section 23.1.2.4, “Installing Connector/ODBC from a source distribution”, to
build the driver from the original source code. You can
contribute the binaries you create to MySQL by sending a mail
message to Using a binary distribution offers the most straightforward method for installing Connector/ODBC. If you want more control over the driver, the installation location and or to customize elements of the driver you will need to build and install from the source. See the Section 23.1.2.4, “Installing Connector/ODBC from a source distribution”. Before installing the Connector/ODBC drivers on Windows you should ensure that your Microsoft Data Access Components (MDAC) are up to date. You can obtain the latest version from the Microsoft Data Access and Storage Web site. There are three available distribution types to use when installing for Windows. The contents in each case are identical, it is only the installation method which is different.
The installer packages offer a very simple method for installing the Connector/ODBC drivers. If you have downloaded the zipped installer then you must extract the installer application. The basic installation process is identical for both installers. You should follow these steps to complete the installation:
Now the installation is complete, you can continue to configure your ODBC connections using Section 23.1.3, “Connector/ODBC Configuration”. If you have downloaded the Zipped DLL package then you must install the individual files required for Connector/ODBC operation manually. Once you have unzipped the installation files, you can either perform this operation by hand, executing each statement individually, or you can use the included Batch file to perform an installation to the default locations. To install using the Batch file:
If you want to copy the files to an alternative location - for example, to run or test different versions of the Connector/ODBC driver on the same machine, then you must copy the files by hand. It is however not recommended to install these files in a non-standard location. To copy the files by hand to the default installation location use the following steps:
On Windows, you may get the following error when trying to install the older MyODBC 2.50 driver: An error occurred while copying C:\WINDOWS\SYSTEM\MFC30.DLL. Restart Windows and try installing again (before running any applications which use ODBC)
The reason for the error is that another application is
currently using the ODBC system. Windows may not allow you
to complete the installation. In most cases, you can
continue by pressing There are two methods available for installing Connector/ODBC on Unix from a binary distribution. For most Unix environments you will need to use the tarball distribution. For Linux systems, there is also an RPM distribution available.
To install the driver from a tarball distribution
( shell>
Read the installation instructions in the
shell>
Then proceed on to
Section 23.1.3.4, “Configuring a Connector/ODBC DSN on Unix”,
to configure the DSN for Connector/ODBC. For more
information, refer to the
To install or upgrade Connector/ODBC from an RPM
distribution on Linux, simply download the RPM distribution
of the latest version of Connector/ODBC and follow the
instructions below. Use su root to become
If you are installing for the first time: shell> If the driver exists, upgrade it like this: shell>
If there is any dependency error for MySQL client library,
This installs the driver libraries and related documents to
To uninstall the driver,
become shell> Mac OS X is based on the FreeBSD operating system, and you can normally use the MySQL network port for connecting to MySQL servers on other hosts. Installing the Connector/ODBC driver enables you to connect to MySQL databases on any platform through the ODBC interface. You should only need to install the Connector/ODBC driver when your application requires an ODBC interface. Applications that require or can use ODBC (and therefore the Connector/ODBC driver) include ColdFusion, Filemaker Pro, 4th Dimension and many other applications.
Mac OS X includes its own ODBC manager, based on the
You can install Connector/ODBC on a Mac OS X or Mac OS X
Server computer by using the binary distribution. The
package is available as a compressed disk image
(
Installing Connector/ODBC from a source distribution gives you greater flexibility in the contents and installation location of the Connector/ODBC components. It also enables you to build and install Connector/ODBC on platforms where a pre-compiled binary is not available. Connector/ODBC sources are available either as a downloadable package, or through the revision control system used by the Connector/ODBC developers. You should only need to install Connector/ODBC from source on Windows if you want to change or modify the source or installation. If you are unsure whether to install from source, please use the binary installation detailed in Section 23.1.2.3.1, “Installing Connector/ODBC from a Binary Distribution on Windows”. Installing Connector/ODBC from source on Windows requires a number of different tools and packages:
Connector/ODBC source distributions include
To build the driver, use this procedure:
Note:
After the driver libraries are copied/installed to the
system directory, you can test whether the libraries are
properly built by using the samples provided in the
C:\>
You need the following tools to build MySQL from source on Unix:
Once you have all the required files, unpack the source files to a separate directory, you then have to run configure and build the library using make. The configure script gives you a great deal of control over how you configure your Connector/ODBC build. Typically you do this using options on the configure command line. You can also affect configure using certain environment variables. For a list of options and environment variables supported by configure, run this command: shell> Some of the more commonly used configure options are described here:
The final configuration command looks something like this: shell> There are a number of other options that you need, or want, to set when configuring the Connector/ODBC driver before it is built.
To build the driver libraries, you have to just execute make. shell>
If any errors occur, correct them and continue the build
process. If you aren't able to build, then send a detailed
email to
On most platforms, MySQL does not build or support
In cases like this, you have to download the MySQL distribution and configure it with these options: --without-server --enable-shared
To build shared driver libraries, you must specify the
If you have configured with the
shell>
Make sure to change
This builds and places the
shell> To build the thread-safe driver library: shell> To install the driver libraries, execute the following command: shell> That command installs one of the following sets of libraries: For Connector/ODBC 3.51:
For thread-safe Connector/ODBC 3.51:
For MyODBC 2.5.0:
For more information on build process, refer to the
To run the basic samples provided in the distribution with the libraries that you built, use the following command: shell>
Before running the tests, create the DSN 'myodbc3' in
You can even modify the
To build the driver on Mac OS X (Darwin), make use of the following configure example: shell>
The command assumes that the
On Mac OS X, shell> To build the thread-safe driver library: shell>
Make sure to change the In Apple's version of GCC, both cc and gcc are actually symbolic links to gcc3.
Copy this library to the You can cross-check the output shared-library properties using this command: shell> To build the driver on HP-UX 10.x or 11.x, make use of the following configure example: If using cc: shell> If using gcc: shell>
Once the driver is built, cross-check its attributes using
chatr .libs/libmyodbc3.sl to determine
whether you need to have set the MySQL client library path
using the To build the driver on AIX, make use of the following configure example: shell> NOTE: For more information about how to build and set up the static and shared libraries across the different platforms refer to ' Using static and shared libraries across platforms'. Caution: You should read this section only if you are interested in helping us test our new code. If you just want to get MySQL Connector/ODBC up and running on your system, you should use a standard release distribution. To be able to access the Connector/ODBC source tree, you must have Subversion installed. Subversion is freely available from http://subversion.tigris.org/. To build from the source trees, you need the following tools:
The most recent development source tree is available from our public Subversion trees at http://dev.mysql.com/tech-resources/sources.html. To checkout out the Connector/ODBC sources, change to the directory where you want the copy of the Connector/ODBC tree to be stored, then use the following command: shell> svn co http://svn.mysql.com/svnpublic/connector-odbc3
You should now have a copy of the entire Connector/ODBC source
tree in the directory shell>
For more information on how to build, refer to the
When the build is done, run make install to install the Connector/ODBC 3.51 driver on your system.
If you have gotten to the make stage and
the distribution does not compile, please report it to
On Windows, make use of Windows Makefiles
After the initial checkout operation to get the source tree, you should run svn update periodically update your source according to the latest version.
Before you connect to a MySQL database using the Connector/ODBC driver you must configure an ODBC Data Source Name. The DSN associates the various configuration parameters required to communicate with a database to a specific name. You use the DSN in an application to communicate with the database, rather than specifying individual parameters within the application itself. DSN information can be user specific, system specific, or provided in a special file. ODBC data source names are configured in different ways, depending on your platform and ODBC driver. A Data Source Name associates the configuration parameters for communicating with a specific database. Generally a DSN consists of the following parameters:
In addition, different ODBC drivers, including Connector/ODBC, may accept additional driver-specific options and parameters. There are three types of DSN:
DSN information is stored in different locations depending on your platform and environment.
The
Different editions and versions of Windows store the
To open the
To open the
To open the
Irrespective of your Windows version, you should be presented
the ![]()
Within Windows XP, you can add the
Within both Windows Server 2003 and Windows XP you may want to
permanently add the
To add and configure a new Connector/ODBC data source on
Windows, use the
A completed DSN configuration may look like this: ![]()
You can verify the connection using the parameters you have
entered by clicking the button. If
the connection could be made successfully, you will be
notified with a If the connection failed, you can obtain more information on the test and why it may have failed by clicking the button to show additional error messages. You can configure a number of options for a specific DSN by using either the or tabs in the DSN configuration dialog. The dialog can be seen below. ![]() The three options you can configure are:
The tab enables you to configure Connector/ODBC connection parameters. Refer to Section 23.1.3.5, “Connector/ODBC Connection Parameters”, for information about the meaning of these options. ![]() This section answers Connector/ODBC connection-related questions.
To configure a DSN on Mac OS X you should use the ODBC Administrator. If you have Mac OS X 10.2 or earlier, refer to Section 23.1.3.4, “Configuring a Connector/ODBC DSN on Unix”. Select whether you want to create a User DSN or a System DSN. If you want to add a System DSN, you may need to authenticate with the system. You must click the padlock and enter a user and password with administrator privileges.
A completed DSN configuration may look like this: ![]() You can configure additional ODBC options to your DSN by adding further keyword/value pairs and setting the corresponding values. See Section 23.1.3.5, “Connector/ODBC Connection Parameters”.
On ; ; odbc.ini configuration for Connector/ODBC and Connector/ODBC 3.51 drivers ; [ODBC Data Sources] myodbc = MyODBC 2.50 Driver DSN myodbc3 = MyODBC 3.51 Driver DSN [myodbc] Driver = /usr/local/lib/libmyodbc.so Description = MyODBC 2.50 Driver DSN SERVER = localhost PORT = USER = root Password = Database = test OPTION = 3 SOCKET = [myodbc3] Driver = /usr/local/lib/libmyodbc3.so Description = Connector/ODBC 3.51 Driver DSN SERVER = localhost PORT = USER = root Password = Database = test OPTION = 3 SOCKET = [Default] Driver = /usr/local/lib/libmyodbc3.so Description = Connector/ODBC 3.51 Driver DSN SERVER = localhost PORT = USER = root Password = Database = test OPTION = 3 SOCKET = Refer to the Section 23.1.3.5, “Connector/ODBC Connection Parameters”, for the list of connection parameters that can be supplied.
Note: If you are using
In some cases when using Data source name not found and no default driver specified
If this happens, make sure the export ODBCINI=/usr/local/etc/odbc.ini export ODBCSYSINI=/usr/local/etc
You can specify the parameters in the following tables for
Connector/ODBC when configuring a DSN. Users on Windows can use
the Options and Advanced panels when configuring a DSN to set
these parameters; see the table for information on which options
relate to which fields and checkboxes. On Unix and Mac OS X, use
the parameter name and value as the keyword/value pair in the
DSN configuration. Alternatively, you can set these parameters
within the
The
To select multiple options, add together their values. For
example, setting
The following table shows some recommended
You can connect to the MySQL server using SQLDriverConnect, by
specifying the For MyODBC 2.50: ConnectionString = "DRIVER={MySQL};\
SERVER=localhost;\
DATABASE=test;\
USER=venu;\
PASSWORD=venu;\
OPTION=3;"For Connector/ODBC 3.51: ConnectionString = "DRIVER={MySQL ODBC 3.51 Driver};\
SERVER=localhost;\
DATABASE=test;\
USER=venu;\
PASSWORD=venu;\
OPTION=3;"If your programming language converts backslash followed by whitespace to a space, it is preferable to specify the connection string as a single long string, or to use a concatenation of multiple strings that does not add spaces in between. For example: ConnectionString = "DRIVER={MySQL ODBC 3.51 Driver};"
"SERVER=localhost;"
"DATABASE=test;"
"USER=venu;"
"PASSWORD=venu;"
"OPTION=3;"Note. Note that on Mac OS X you may need to specify the full path to the Connector/ODBC driver library. Refer to the Section 23.1.3.5, “Connector/ODBC Connection Parameters”, for the list of connection parameters that can be supplied. Connection pooling enables the ODBC driver to re-use existing connections to a given database from a pool of connections, instead of opening a new connection each time the database is accessed. By enabling connection pooling you can improve the overall performance of your application by lowering the time taken to open a connection to a database in the connection pool. For more information about connection pooling: http://support.microsoft.com/default.aspx?scid=kb;EN-US;q169470.
If you encounter difficulties or problems with Connector/ODBC,
you should start by making a log file from the To enable the trace option on Windows:
To enable the trace option on Mac OS X 10.3 or later you
should use the
To enable the trace option on Mac OS X 10.2 (or earlier) or
Unix you must add the
To generate a Connector/ODBC log, do the following:
If you need help determining what is wrong, see Section 23.1.7.1, “Connector/ODBC Community Support”.
Once you have configured a DSN to provide access to a database, how you access and use that connection is dependent on the application or programming language. As ODBC is a standardized interface, any application or language that supports ODBC can use the DSN and connect to the configured database. Interacting with a MySQL server from an applications using the Connector/ODBC typically involves the following operations:
Most applications use some variation of these steps. The basic application steps are shown in the following diagram: ![]() A typical installation situation where you would install Connector/ODBC is when you want to access a database on a Linux or Unix host from a Windows machine.
As an example of the process required to set up access between
two machines, the steps below take you through the basic steps.
These instructions assume that you want to connect to system
ALPHA from system BETA with a username and password of
On system ALPHA (the MySQL server) follow these steps:
On system BETA (the Connector/ODBC client), follow these steps:
Once you have configured your Connector/ODBC DSN, you can access your MySQL database through any application that supports the ODBC interface, including programming languages and third-party applications. This section contains guides and help on using Connector/ODBC with various ODBC-compatible tools and applications, including Microsoft Word, Microsoft Excel and Adobe/Macromedia ColdFusion. Connector/ODBC has been tested with the following applications:
If you know of any other applications that work with
Connector/ODBC, please send mail to
You can use MySQL database with Microsoft Access using Connector/ODBC. The MySQL database can be used as an import source, an export source, or as a linked table for direct use within an Access application, so you can use Access as the front-end interface to a MySQL database. To export a table of data from an Access database to MySQL, follow these instructions:
Microsoft Access connects to the MySQL Server through this data source and exports new tables and or data. To import a table or tables from MySQL to Access, follow these instructions:
You can use Microsoft Access as a front end to a MySQL database by linking tables within your Microsoft Access database to tables that exist within your MySQL database. When a query is requested on a table within Access, ODBC is used to execute the queries on the MySQL database instead. To create a linked table:
Once the process has been completed, you can now build interfaces and queries to the linked tables just as you would for any Access database. Use the following procedure to view or to refresh links when the structure or location of a linked table has changed. The Linked Table Manager lists the paths to all currently linked tables. To view or refresh links:
Microsoft Access confirms a successful refresh or, if the
table wasn't found, displays the To change the path for a set of linked tables:
You can use Microsoft Word and Microsoft Excel to access information from a MySQL database using Connector/ODBC. Within Microsoft Word, this facility is most useful when importing data for mailmerge, or for tables and data to be included in reports. Within Microsoft Excel, you can execute queries on your MySQL server and import the data directly into an Excel Worksheet, presenting the data as a series of rows and columns. With both applications, data is accessed and imported into the application using Microsoft Query , which enables you to execute a query though an ODBC source. You use Microsoft Query to build the SQL statement to be executed, selecting the tables, fields, selection criteria and sort order. For example, to insert information from a table in the World test database into an Excel spreadsheet, using the DSN samples shown in Section 23.1.3, “Connector/ODBC Configuration”:
The same process can be used to import data into a Word document, where the data will be inserted as a table. This can be used for mail merge purposes (where the field data is read from a Word table), or where you want to include data and reports within a report or other document. Crystal Reports can use an ODBC DSN to connect to a database from which you to extract data and information for reporting purposes. NoteThere is a known issue with certain versions of Crystal Reports where the application is unable to open and browse tables and fields through an ODBC connection. Before using Crystal Reports with MySQL, please ensure that you have update to the latest version, including any outstanding service packs and hotfixes. For more information on this issue, see the Business) Objects Knowledgebase for more information. For example, to create a simple crosstab report within Crystal Reports XI, you should follow these steps:
Once the ODBC connection has been opened within Crystal Reports, you can browse and add any fields within the available tables into your reports. With a suitable ODBC Manager and the Connector/ODBC driver installed, any programming language or environment that can support ODBC should be able to connect to a MySQL database through Connector/ODBC. This includes, but is certainly not limited to, Microsoft support languages (including Visual Basic, C# and interfaces such as ODBC.NET), Perl (through the DBI module, and the DBD::ODBC driver). This section contains simple examples of the use of MySQL ODBC 3.51 Driver with ADO, DAO and RDO.
The following ADO (ActiveX Data Objects) example creates a
table Private Sub myodbc_ado_Click()
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim fld As ADODB.Field
Dim sql As String
'connect to MySQL server using MySQL ODBC 3.51 Driver
Set conn = New ADODB.Connection
conn.ConnectionString = "DRIVER={MySQL ODBC 3.51 Driver};"_
& "SERVER=localhost;"_
& " DATABASE=test;"_
& "UID=venu;PWD=venu; OPTION=3"
conn.Open
'create table
conn.Execute "DROP TABLE IF EXISTS my_ado"
conn.Execute "CREATE TABLE my_ado(id int not null primary key, name varchar(20)," _
& "txt text, dt date, tm time, ts timestamp)"
'direct insert
conn.Execute "INSERT INTO my_ado(id,name,txt) values(1,100,'venu')"
conn.Execute "INSERT INTO my_ado(id,name,txt) values(2,200,'MySQL')"
conn.Execute "INSERT INTO my_ado(id,name,txt) values(3,300,'Delete')"
Set rs = New ADODB.Recordset
rs.CursorLocation = adUseServer
'fetch the initial table ..
rs.Open "SELECT * FROM my_ado", conn
Debug.Print rs.RecordCount
rs.MoveFirst
Debug.Print String(50, "-") & "Initial my_ado Result Set " & String(50, "-")
For Each fld In rs.Fields
Debug.Print fld.Name,
Next
Debug.Print
Do Until rs.EOF
For Each fld In rs.Fields
Debug.Print fld.Value,
Next
rs.MoveNext
Debug.Print
Loop
rs.Close
'rs insert
rs.Open "select * from my_ado", conn, adOpenDynamic, adLockOptimistic
rs.AddNew
rs!Name = "Monty"
rs!txt = "Insert row"
rs.Update
rs.Close
'rs update
rs.Open "SELECT * FROM my_ado"
rs!Name = "update"
rs!txt = "updated-row"
rs.Update
rs.Close
'rs update second time..
rs.Open "SELECT * FROM my_ado"
rs!Name = "update"
rs!txt = "updated-second-time"
rs.Update
rs.Close
'rs delete
rs.Open "SELECT * FROM my_ado"
rs.MoveNext
rs.MoveNext
rs.Delete
rs.Close
'fetch the updated table ..
rs.Open "SELECT * FROM my_ado", conn
Debug.Print rs.RecordCount
rs.MoveFirst
Debug.Print String(50, "-") & "Updated my_ado Result Set " & String(50, "-")
For Each fld In rs.Fields
Debug.Print fld.Name,
Next
Debug.Print
Do Until rs.EOF
For Each fld In rs.Fields
Debug.Print fld.Value,
Next
rs.MoveNext
Debug.Print
Loop
rs.Close
conn.Close
End Sub
The following DAO (Data Access Objects) example creates a
table Private Sub myodbc_dao_Click()
Dim ws As Workspace
Dim conn As Connection
Dim queryDef As queryDef
Dim str As String
'connect to MySQL using MySQL ODBC 3.51 Driver
Set ws = DBEngine.CreateWorkspace("", "venu", "venu", dbUseODBC)
str = "odbc;DRIVER={MySQL ODBC 3.51 Driver};"_
& "SERVER=localhost;"_
& " DATABASE=test;"_
& "UID=venu;PWD=venu; OPTION=3"
Set conn = ws.OpenConnection("test", dbDriverNoPrompt, False, str)
'Create table my_dao
Set queryDef = conn.CreateQueryDef("", "drop table if exists my_dao")
queryDef.Execute
Set queryDef = conn.CreateQueryDef("", "create table my_dao(Id INT AUTO_INCREMENT PRIMARY KEY, " _
& "Ts TIMESTAMP(14) NOT NULL, Name varchar(20), Id2 INT)")
queryDef.Execute
'Insert new records using rs.addNew
Set rs = conn.OpenRecordset("my_dao")
Dim i As Integer
For i = 10 To 15
rs.AddNew
rs!Name = "insert record" & i
rs!Id2 = i
rs.Update
Next i
rs.Close
'rs update..
Set rs = conn.OpenRecordset("my_dao")
rs.Edit
rs!Name = "updated-string"
rs.Update
rs.Close
'fetch the table back...
Set rs = conn.OpenRecordset("my_dao", dbOpenDynamic)
str = "Results:"
rs.MoveFirst
While Not rs.EOF
str = " " & rs!Id & " , " & rs!Name & ", " & rs!Ts & ", " & rs!Id2
Debug.Print "DATA:" & str
rs.MoveNext
Wend
'rs Scrolling
rs.MoveFirst
str = " FIRST ROW: " & rs!Id & " , " & rs!Name & ", " & rs!Ts & ", " & rs!Id2
Debug.Print str
rs.MoveLast
str = " LAST ROW: " & rs!Id & " , " & rs!Name & ", " & rs!Ts & ", " & rs!Id2
Debug.Print str
rs.MovePrevious
str = " LAST-1 ROW: " & rs!Id & " , " & rs!Name & ", " & rs!Ts & ", " & rs!Id2
Debug.Print str
'free all resources
rs.Close
queryDef.Close
conn.Close
ws.Close
End Sub
The following RDO (Remote Data Objects) example creates a
table Dim rs As rdoResultset
Dim cn As New rdoConnection
Dim cl As rdoColumn
Dim SQL As String
'cn.Connect = "DSN=test;"
cn.Connect = "DRIVER={MySQL ODBC 3.51 Driver};"_
& "SERVER=localhost;"_
& " DATABASE=test;"_
& "UID=venu;PWD=venu; OPTION=3"
cn.CursorDriver = rdUseOdbc
cn.EstablishConnection rdDriverPrompt
'drop table my_rdo
SQL = "drop table if exists my_rdo"
cn.Execute SQL, rdExecDirect
'create table my_rdo
SQL = "create table my_rdo(id int, name varchar(20))"
cn.Execute SQL, rdExecDirect
'insert - direct
SQL = "insert into my_rdo values (100,'venu')"
cn.Execute SQL, rdExecDirect
SQL = "insert into my_rdo values (200,'MySQL')"
cn.Execute SQL, rdExecDirect
'rs insert
SQL = "select * from my_rdo"
Set rs = cn.OpenResultset(SQL, rdOpenStatic, rdConcurRowVer, rdExecDirect)
rs.AddNew
rs!id = 300
rs!Name = "Insert1"
rs.Update
rs.Close
'rs insert
SQL = "select * from my_rdo"
Set rs = cn.OpenResultset(SQL, rdOpenStatic, rdConcurRowVer, rdExecDirect)
rs.AddNew
rs!id = 400
rs!Name = "Insert 2"
rs.Update
rs.Close
'rs update
SQL = "select * from my_rdo"
Set rs = cn.OpenResultset(SQL, rdOpenStatic, rdConcurRowVer, rdExecDirect)
rs.Edit
rs!id = 999
rs!Name = "updated"
rs.Update
rs.Close
'fetch back...
SQL = "select * from my_rdo"
Set rs = cn.OpenResultset(SQL, rdOpenStatic, rdConcurRowVer, rdExecDirect)
Do Until rs.EOF
For Each cl In rs.rdoColumns
Debug.Print cl.Value,
Next
rs.MoveNext
Debug.Print
Loop
Debug.Print "Row count="; rs.RowCount
'close
rs.Close
cn.Close
End SubThis section contains simple examples that demonstrate the use of Connector/ODBC drivers with ODBC.NET.
The following sample creates a table
/**
* @sample : mycon.cs
* @purpose : Demo sample for ODBC.NET using Connector/ODBC
* @author : Venu,
The following sample creates a table
' @sample : myvb.vb
' @purpose : Demo sample for ODBC.NET using Connector/ODBC
' @author : Venu, This section provides reference material for the Connector/ODBC API, showing supported functions and methods, supported MySQL column types and the corresponding native type in Connector/ODBC, and the error codes returned by Connector/ODBC when a fault occurs. This section summarizes ODBC routines, categorized by functionality. For the complete ODBC API reference, please refer to the ODBC Programer's Reference at http://msdn.microsoft.com/library/en-us/odbc/htm/odbcabout_this_manual.asp.
An application can call NoteFor backward compatibility, the Connector/ODBC 3.51 driver supports all deprecated functions. The following tables list Connector/ODBC API calls grouped by task: Connecting to a data source:
Obtaining information about a driver and data source:
Setting and retrieving driver attributes:
Preparing SQL requests:
Submitting requests:
Retrieving results and information about results:
Retrieving error or diagnostic information:
Obtaining information about the data source's system tables (catalog functions) item:
Performing transactions:
Terminating a statement:
Terminating a connection:
The following table illustrates how driver maps the server data types to default SQL and C data types:
The following tables lists the error codes returned by the driver apart from the server errors.
Here are some common notes and tips for using Connector/ODBC within different environments, applications and tools. The notes provided here are based on the experiences of Connector/ODBC developers and users. This section provides help with common queries and areas of functionality in MySQL and how to use them with Connector/ODBC.
Obtaining the value of column that uses
For example, using Connector/ODBC you would execute two
separate statements, the INSERT INTO tbl (auto,text) VALUES(NULL,'text'); SELECT LAST_INSERT_ID();
If you do not require the value within your application, but
do require the value as part of another
INSERT INTO tbl (auto,text) VALUES(NULL,'text'); INSERT INTO tbl2 (id,text) VALUES(LAST_INSERT_ID(),'text'); Certain ODBC applications (including Delphi and Access) may have trouble obtaining the auto-increment value using the previous examples. In this case, try the following statement as an alternative: SELECT * FROM tbl WHERE auto IS NULL; See Section 22.2.14.3, “How to Get the Unique ID for the Last Inserted Row”.
Support for the
On other platforms, you can enable the dynamic cursor by
adding The Connector/ODBC driver has been optimized to provide very fast performance. If you experience problems with the performance of Connector/ODBC, or notice a large amount of disk activity for simple queries, there are a number of aspects you should check:
For more information on how to set the query timeout on Microsoft Windows when executing queries through an ODBC connection, read the Microsoft knowledgebase document at http://support.microsoft.com/default.aspx?scid=kb%3Ben-us%3B153756.
Most programs should work with Connector/ODBC, but for each of those listed here, there are specific notes and tips to improve or enhance the way you work with Connector/ODBC and these applications. With all applications you should ensure that you are using the latest Connector/ODBC drivers, ODBC Manager and any supporting libraries and interfaces used by your application. For example, on Windows, using the latest version of Microsoft Data Access Components (MDAC) will improve the compatibility with ODBC in general, and with the Connector/ODBC driver.
The majority of Microsoft applications have been tested with Connector/ODBC, including Microsoft Office, Microsoft Access and the various programming languages supported within ASP and Microsoft Visual Studio. To improve the integration between Microsoft Access and MySQL through Connector/ODBC:
Some external articles and tips that may be useful when using Access, ODBC and Connector/ODBC:
MySQL Enterprise MySQL Enterprise subscribers will find more information about using ODBC with Access in Knowledge Base articles such as Use MySQL-Specific Syntax with Microsoft Access. To subscribe to MySQL Enterprise see http://www.mysql.com/products/enterprise/advisors.html. If you have problems importing data into Microsoft Excel, particularly numerical, date, and time values, this is probably because of a bug in Excel, where the column type of the source data is used to determine the data type when that data is inserted into a cell within the worksheet. The result is that Excel incorrectly identifies the content and this affects both the display format and the data when it is used within calculations.
To address this issue, use the
However, even with this option, some data may be incorrectly
formatted, even though the source data remains unchanged.
Use the To be able to update a table, you must define a primary key for the table.
Visual Basic with ADO can't handle big integers. This means
that some queries like MySQL Enterprise MySQL Enterprise subscribers can find a discussion about using VBA in the Knowledge Base article, MySQL-Specific Syntax with VBA. To subscribe to MySQL Enterprise see http://www.mysql.com/products/enterprise/advisors.html.
If you have a
When you are coding with the ADO API and Connector/ODBC, you
need to pay attention to some default properties that aren't
supported by the MySQL server. For example, using the
Dim myconn As New ADODB.Connection Dim myrs As New Recordset Dim mySQL As String Dim myrows As Long myconn.Open "DSN=MyODBCsample" mySQL = "SELECT * from user" myrs.Source = mySQL Set myrs.ActiveConnection = myconn myrs.CursorLocation = adUseClient myrs.Open myrows = myrs.RecordCount myrs.Close myconn.Close
Another workaround is to use a
To find the number of rows affected by a specific SQL
statement in ADO, use the For information, see ActiveX Data Objects(ADO) Frequently Asked Questions.
You should select the For more information about how to access MySQL via ASP using Connector/ODBC, refer to the following articles: A Frequently Asked Questions list for ASP can be found at http://support.microsoft.com/default.aspx?scid=/Support/ActiveServer/faq/data/adofaq.asp. Some articles that may help with Visual Basic and ASP:
With all Borland applications where the Borland Database Engine (BDE) is used, follow these steps to improve compatibility:
When you start a query, you can use the
Also, here is some potentially useful Delphi code that sets
up both an ODBC entry and a BDE entry for Connector/ODBC.
The BDE entry requires a BDE Alias Editor that is free at a
Delphi Super Page near you. (Thanks to Bryan Brunton
fReg:= TRegistry.Create;
fReg.OpenKey('\Software\ODBC\ODBC.INI\DocumentsFab', True);
fReg.WriteString('Database', 'Documents');
fReg.WriteString('Description', ' ');
fReg.WriteString('Driver', 'C:\WINNT\System32\myodbc.dll');
fReg.WriteString('Flag', '1');
fReg.WriteString('Password', '');
fReg.WriteString('Port', ' ');
fReg.WriteString('Server', 'xmark');
fReg.WriteString('User', 'winuser');
fReg.OpenKey('\Software\ODBC\ODBC.INI\ODBC Data Sources', True);
fReg.WriteString('DocumentsFab', 'MySQL');
fReg.CloseKey;
fReg.Free;
Memo1.Lines.Add('DATABASE NAME=');
Memo1.Lines.Add('USER NAME=');
Memo1.Lines.Add('ODBC DSN=DocumentsFab');
Memo1.Lines.Add('OPEN MODE=READ/WRITE');
Memo1.Lines.Add('BATCH COUNT=200');
Memo1.Lines.Add('LANGDRIVER=');
Memo1.Lines.Add('MAX ROWS=-1');
Memo1.Lines.Add('SCHEMA CACHE DIR=');
Memo1.Lines.Add('SCHEMA CACHE SIZE=8');
Memo1.Lines.Add('SCHEMA CACHE TIME=-1');
Memo1.Lines.Add('SQLPASSTHRU MODE=SHARED AUTOCOMMIT');
Memo1.Lines.Add('SQLQRYMODE=');
Memo1.Lines.Add('ENABLE SCHEMA CACHE=FALSE');
Memo1.Lines.Add('ENABLE BCD=FALSE');
Memo1.Lines.Add('ROWSET SIZE=20');
Memo1.Lines.Add('BLOBS TO CACHE=64');
Memo1.Lines.Add('BLOB SIZE=32');
AliasEditor.Add('DocumentsFab','MySQL',Memo1.Lines);
The following information is taken from the ColdFusion documentation:
Use the following information to configure ColdFusion Server
for Linux to use the
ColdFusion version 4.5.1 allows you to us the ColdFusion
Administrator to add the MySQL data source. However, the
driver is not included with ColdFusion version 4.5.1. Before
the MySQL driver appears in the ODBC data sources drop-down
list, you must build and copy the Connector/ODBC driver to
The Contrib directory contains the program
For more information and guides on using ColdFusion and Connector/ODBC, see the following external sites: Open Office (http://www.openoffice.org) How-to: MySQL + OpenOffice. How-to: OpenOffice + MyODBC + unixODBC. Sambar Server (http://www.sambarserver.info) How-to: MyODBC + SambarServer + MySQL. The following section details some common errors and their suggested fix or alternative solution. If you are still experiencing problems, use the Connector/ODBC mailing list; see Section 23.1.7.1, “Connector/ODBC Community Support”. Many problems can be resolved by upgrading your Connector/ODBC drivers to the latest available release. On Windows, you should also make sure that you have the latest versions of the Microsoft Data Access Components (MDAC) installed. Questions
Questions and Answers 24.1.6.3.1: Are MyODBC 2.50 applications compatible with Connector/ODBC 3.51? Applications based on MyODBC 2.50 should work fine with Connector/ODBC 3.51 and later versions. If you find something is not working with the latest version of Connector/ODBC which previously worked under an earlier version, please file a bug report. See Section 23.1.7.2, “How to Report Connector/ODBC Problems or Bugs”. 24.1.6.3.2:
I have installed Connector/ODBC on Windows XP x64 Edition
or Windows Server 2003 R2 x64. The installation completed
successfully, but the Connector/ODBC driver does not
appear in
This is not a bug, but is related to the way Windows x64
editions operate with the ODBC driver. On Windows x64
editions, the Connector/ODBC driver is installed in the
On Windows x64 editions, you should use the ODBC
administration tool located at
This issue was originally reported as Bug#20301. 24.1.6.3.3:
When connecting or using the
button in
This error can be raised by a number of different issues,
including server problems, network problems, and firewall
and port blocking problems. For more information, see
Section B.1.2.2, “ 24.1.6.3.4:
The following error is reported when using transactions:
This error indicates that you are trying to use
transactions with a MySQL table that does not support
transactions. Transactions are supported within MySQL when
using the You should check the following before continuing:
24.1.6.3.5:
The following error is reported when I submit a query:
This occurs because the application is using the old MyODBC 2.50 version, and it did not set the cursor name explicitly through SQLSetCursorName. The fix is to upgrade to Connector/ODBC 3.51 version. 24.1.6.3.6:
Access reports records as
If the inserted or updated records are shown as
24.1.6.3.7: How do I handle Write Conflicts or Row Location errors?
If you see the following errors, select the
Write Conflict. Another user has changed your data. Row cannot be located for updating. Some values may have been changed since it was last read. 24.1.6.3.8:
Exporting data from Access 97 to MySQL reports a
This error is specific to Access 97 and versions of Connector/ODBC earlier than 3.51.02. Update to the latest version of the Connector/ODBC driver to resolve this problem. 24.1.6.3.9:
Exporting data from Microsoft DTS to MySQL reports a
This error occurs only with MySQL tables using the
24.1.6.3.10: Using ODBC.NET with Connector/ODBC, while fetching empty string (0 length), it starts giving the SQL_NO_DATA exception. You can get the patch that addresses this problem from http://support.microsoft.com/default.aspx?scid=kb;EN-US;q319243. 24.1.6.3.11:
Using
This error occurs because the 24.1.6.3.12:
Using the
The A simple example can be found from http://www.dwam.net/iishelp/ado/docs/adomth02_4.htm 24.1.6.3.13:
Access Returns In most cases, this can be solved by doing one of the following things:
If these strategies don't help, you should start by making a log file from the ODBC manager (the log you get when requesting logs from ODBCADMIN) and a Connector/ODBC log to help you figure out why things go wrong. For instructions, see Section 23.1.3.8, “Getting an ODBC Trace File”. 24.1.6.3.14: When linking an application directly to the Connector/ODBC library under Unix/Linux, the application crashes. Connector/ODBC 3.51 under Unix/Linux is not compatible with direct application linking. You must use a driver manager, such as iODBC or unixODBC to connect to an ODBC source. 24.1.6.3.15:
Applications in the Microsoft Office suite are unable to
update tables that have
This is a known issue with Connector/ODBC. You must ensure
that the field has a default value (rather than
24.1.6.3.16:
When connecting Connector/ODBC 5.x (Beta) to a MySQL 4.x
server, the error
Connector/ODBC 5.x is designed to work with MySQL 5.0 or
later, taking advantage of the
24.1.6.3.17:
When calling
The There are many different places where you can get support for using Connector/ODBC. You should always try the Connector/ODBC Mailing List or Connector/ODBC Forum. See Section 23.1.7.1, “Connector/ODBC Community Support”, for help before reporting a specific bug or issue to MySQL.
MySQL AB provides assistance to the user community by means of
its mailing lists. For Connector/ODBC-related issues, you can
get help from experienced users by using the
For information about subscribing to MySQL mailing lists or to browse list archives, visit http://lists.mysql.com/. See Section 1.7.1, “MySQL Mailing Lists”. Community support from experienced users is also available through the ODBC Forum. You may also find help from other users in the other MySQL Forums, located at http://forums.mysql.com. See Section 1.7.2, “MySQL Community Support at the MySQL Forums”.
If you encounter difficulties or problems with Connector/ODBC,
you should start by making a log file from the
Check the Connector/ODBC trace file to find out what could be
wrong. You should be able to determine what statements were
issued by searching for the string
You should also try issuing the statements from the
mysql client program or from
If you find out something is wrong, please only send the
relevant rows (maximum 40 rows) to the You should ideally include the following information with the email:
Remember that the more information you can supply to us, the more likely it is that we can fix the problem! Also, before posting the bug, check the MyODBC mailing list archive at http://lists.mysql.com/myodbc.
If you are unable to find out what's wrong, the last option is
to create an archive in tar or Zip format
that contains a Connector/ODBC trace file, the ODBC log file,
and a If you can create a program that also demonstrates the problem, please include it in the archive as well. If the program works with another SQL server, you should include an ODBC log file where you perform exactly the same SQL statements so that we can compare the results between the two systems. Remember that the more information you can supply to us, the more likely it is that we can fix the problem.
You can send a patch or suggest a better solution for any
existing code or problems by sending a mail message to
The Connector/ODBC Change History (Changelog) is located with the main Changelog for MySQL. See Section E.3, “MySQL Connector/ODBC (MyODBC) Change History”. Connector/NET enables developers to easily create .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:
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 If you are using MySQL 5.0 or later, and Visual Studio as your development environment, you may want also want to use the MySQL Visual Studio Plugin. The plugin acts as a DDEX (Data Designer Extensibility) provider, enabling you to use the data design tools within Visual Studio to manipulate the schema and objects within a MySQL database. For more information, see Section 23.3, “MySQL Visual Studio Plugin”. NoteConnector/NET 5.1.2 and later include the Visual Studio Plugin by default. There are currently three versions of Connector/NET available:
NoteVersion numbers for MySQL products are formatted as X.X.X. However, Windows tools (Control Panel, properties display) may show the version numbers as XX.XX.XX. 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. 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/1.0.html. On Windows, installation is supported either through a binary installation process or by downloading a Zip file with the Connector/NET components. Before installing, you should ensure that your system is up to date, including installing the latest version of the .NET Framework. 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.
Connector/NET is installed through the use of a Windows
Installer ( To install Connector/NET:
Unless you choose otherwise, Connector/NET is installed in
Depending on your installation type, the installed components will include some or all of the following components:
You may also use the C:\> msiexec /package conector-net.msi /quiet
To provide a progress bar to the user during automatic
installation, but still without presenting the user with a
dialog box of the ability to select options, use the
If you are having problems running the installer, you can
download a .zip file without an installer as an alternative.
That file is called
The .zip file contains the following directories:
There is no installer available for installing the Connector/NET component on your Unix installation. However, the installation is very simple. Before installing, please ensure that you have a working Mono project installation. Note that you should only install the Connector/NET component on Unix environments where you want to connect to a MySQL server through the Mono project. If you are deploying or developing on a different environment such as Java or Perl then you should use a more appropriate connectivity component. See Chapter 23, Connectors, or Chapter 22, APIs and Libraries, for more information. To install Connector/NET on Unix/Mono:
Once installed, applications that are compiled with the
Connector/NET component need no further changes. However, you
must ensure that when you compile your applications you include
the Connector/NET component using the
CautionYou should 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, you should use a standard release distribution. To be able to access the Connector/NET source tree, you must have Subversion installed. Subversion is freely available from http://subversion.tigris.org/. The most recent development source tree is available from our public Subversion trees at http://dev.mysql.com/tech-resources/sources.html. To checkout 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> svn co http://svn.mysql.com/svnpublic/connector-net A Visual Studio project is included in the source which you can use to build Connector/NET. Connector/NET comprises several classes that are used to connect to the database, execute queries and statements, and manage query results. The following are the major classes of Connector/NET:
This section contains basic information and examples for each of the above classes. For a more detailed reference guide please see Section 23.2.4, “Connector/NET Reference”.
Represents a SQL statement to execute against a MySQL database. This class cannot be inherited.
You can reset the
If a
MySqlException
is generated by the method executing a
NotePrior versions of the provider used the '@' symbol to mark parameters in SQL. This is incompatible with MySQL user variables, so the provider now uses the '?' symbol to locate parameters in SQL. To support older code, you can set 'old syntax=yes' on your connection string. If you do this, please be aware that an exception will not be throw if you fail to define a parameter that you intended to use in your SQL. Examples
The following example creates a
MySqlCommand
and a Visual Basic example: Public Sub InsertRow(myConnectionString As String)
" If the connection string is null, use a default.
If myConnectionString = "" Then
myConnectionString = "Database=Test;Data Source=localhost;User Id=username;Password=pass"
End If
Dim myConnection As New MySqlConnection(myConnectionString)
Dim myInsertQuery As String = "INSERT INTO Orders (id, customerId, amount) Values(1001, 23, 30.66)"
Dim myCommand As New MySqlCommand(myInsertQuery)
myCommand.Connection = myConnection
myConnection.Open()
myCommand.ExecuteNonQuery()
myCommand.Connection.Close()
End Sub
C# example: public void InsertRow(string myConnectionString)
{
// If the connection string is null, use a default.
if(myConnectionString == "")
{
myConnectionString = "Database=Test;Data Source=localhost;User Id=username;Password=pass";
}
MySqlConnection myConnection = new MySqlConnection(myConnectionString);
string myInsertQuery = "INSERT INTO Orders (id, customerId, amount) Values(1001, 23, 30.66)";
MySqlCommand myCommand = new MySqlCommand(myInsertQuery);
myCommand.Connection = myConnection;
myConnection.Open();
myCommand.ExecuteNonQuery();
myCommand.Connection.Close();
}
Overload methods for MySqlCommand Initializes a new instance of the MySqlCommand class. Examples The following example creates a MySqlCommand and sets some of its properties. Note
This example shows how to use one of the overloaded versions
of the Visual Basic example: Public Sub CreateMySqlCommand()
Dim myConnection As New MySqlConnection _
("Persist Security Info=False;database=test;server=myServer")
myConnection.Open()
Dim myTrans As MySqlTransaction = myConnection.BeginTransaction()
Dim mySelectQuery As String = "SELECT * FROM MyTable"
Dim myCommand As New MySqlCommand(mySelectQuery, myConnection, myTrans)
myCommand.CommandTimeout = 20
End Sub
C# example: public void CreateMySqlCommand()
{
MySqlConnection myConnection = new MySqlConnection("Persist Security Info=False;
database=test;server=myServer");
myConnection.Open();
MySqlTransaction myTrans = myConnection.BeginTransaction();
string mySelectQuery = "SELECT * FROM myTable";
MySqlCommand myCommand = new MySqlCommand(mySelectQuery, myConnection,myTrans);
myCommand.CommandTimeout = 20;
}
C++ example: public:
void CreateMySqlCommand()
{
MySqlConnection* myConnection = new MySqlConnection(S"Persist Security Info=False;
database=test;server=myServer");
myConnection->Open();
MySqlTransaction* myTrans = myConnection->BeginTransaction();
String* mySelectQuery = S"SELECT * FROM myTable";
MySqlCommand* myCommand = new MySqlCommand(mySelectQuery, myConnection, myTrans);
myCommand->CommandTimeout = 20;
};
Initializes a new instance of the MySqlCommand class.
The base constructor initializes all fields to their default
values. The following table shows initial property values for
an instance of
You can change the value for any of these properties through a separate call to the property. Examples
The following example creates a
Visual Basic example: Public Sub CreateMySqlCommand()
Dim myCommand As New MySqlCommand()
myCommand.CommandType = CommandType.Text
End Sub
C# example: public void CreateMySqlCommand()
{
MySqlCommand myCommand = new MySqlCommand();
myCommand.CommandType = CommandType.Text;
}
Initializes a new instance of the
Parameters: The text of the query.
When an instance of
You can change the value for any of these properties through a separate call to the property. Examples
The following example creates a
Visual Basic example: Public Sub CreateMySqlCommand()
Dim sql as String = "SELECT * FROM mytable"
Dim myCommand As New MySqlCommand(sql)
myCommand.CommandType = CommandType.Text
End Sub
C# example: public void CreateMySqlCommand()
{
string sql = "SELECT * FROM mytable";
MySqlCommand myCommand = new MySqlCommand(sql);
myCommand.CommandType = CommandType.Text;
}
Initializes a new instance of the
Parameters: The text of the query.
Parameters: A
When an instance of
You can change the value for any of these properties through a separate call to the property. Examples
The following example creates a
Visual Basic example: Public Sub CreateMySqlCommand()
Dim conn as new MySqlConnection("server=myServer")
Dim sql as String = "SELECT * FROM mytable"
Dim myCommand As New MySqlCommand(sql, conn)
myCommand.CommandType = CommandType.Text
End Sub
C# example: public void CreateMySqlCommand()
{
MySqlConnection conn = new MySqlConnection("server=myserver")
string sql = "SELECT * FROM mytable";
MySqlCommand myCommand = new MySqlCommand(sql, conn);
myCommand.CommandType = CommandType.Text;
}
Initializes a new instance of the
Parameters: The text of the query.
Parameters: A
Parameters: The
When an instance of
You can change the value for any of these properties through a separate call to the property. Examples
The following example creates a
Visual Basic example: Public Sub CreateMySqlCommand()
Dim conn as new MySqlConnection("server=myServer")
conn.Open();
Dim txn as MySqlTransaction = conn.BeginTransaction()
Dim sql as String = "SELECT * FROM mytable"
Dim myCommand As New MySqlCommand(sql, conn, txn)
myCommand.CommandType = CommandType.Text
End Sub
C# example: public void CreateMySqlCommand()
{
MySqlConnection conn = new MySqlConnection("server=myserver")
conn.Open();
MySqlTransaction txn = conn.BeginTransaction();
string sql = "SELECT * FROM mytable";
MySqlCommand myCommand = new MySqlCommand(sql, conn, txn);
myCommand.CommandType = CommandType.Text;
}
Executes a SQL statement against the connection and returns the number of rows affected. Returns: Number of rows affected You can use ExecuteNonQuery to perform any type of database operation, however any resultsets returned will not be available. Any output parameters used in calling a stored procedure will be populated with data and can be retrieved after execution is complete. For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. For all other types of statements, the return value is -1. Examples The following example creates a MySqlCommand and then executes it using ExecuteNonQuery. The example is passed a string that is a SQL statement (such as UPDATE, INSERT, or DELETE) and a string to use to connect to the data source. Visual Basic example: Public Sub CreateMySqlCommand(myExecuteQuery As String, myConnection As MySqlConnection)
Dim myCommand As New MySqlCommand(myExecuteQuery, myConnection)
myCommand.Connection.Open()
myCommand.ExecuteNonQuery()
myConnection.Close()
End Sub
C# example: public void CreateMySqlCommand(string myExecuteQuery, MySqlConnection myConnection)
{
MySqlCommand myCommand = new MySqlCommand(myExecuteQuery, myConnection);
myCommand.Connection.Open();
myCommand.ExecuteNonQuery();
myConnection.Close();
}
Sends the
Parameters: One of the
When the
The
While the Note
When calling
Returns: A
Sends the
Returns: A
When the
While the Examples
The following example creates a
Visual Basic example: Public Sub CreateMySqlDataReader(mySelectQuery As String, myConnection As MySqlConnection)
Dim myCommand As New MySqlCommand(mySelectQuery, myConnection)
myConnection.Open()
Dim myReader As MySqlDataReader
myReader = myCommand.ExecuteReader()
Try
While myReader.Read()
Console.WriteLine(myReader.GetString(0))
End While
Finally
myReader.Close
myConnection.Close
End Try
End Sub
C# example: public void CreateMySqlDataReader(string mySelectQuery, MySqlConnection myConnection)
{
MySqlCommand myCommand = new MySqlCommand(mySelectQuery, myConnection);
myConnection.Open();
MySqlDataReader myReader;
myReader = myCommand.ExecuteReader();
try
{
while(myReader.Read())
{
Console.WriteLine(myReader.GetString(0));
}
}
finally
{
myReader.Close();
myConnection.Close();
}
}
Creates a prepared version of the command on an instance of MySQL Server. Prepared statements are only supported on MySQL version 4.1 and higher. Calling prepare while connected to earlier versions of MySQL will succeed but will execute the statement in the same way as unprepared. Examples
The following example demonstrates the use of the
Visual Basic example: public sub PrepareExample()
Dim cmd as New MySqlCommand("INSERT INTO mytable VALUES (?val)", myConnection)
cmd.Parameters.Add( "?val", 10 )
cmd.Prepare()
cmd.ExecuteNonQuery()
cmd.Parameters(0).Value = 20
cmd.ExecuteNonQuery()
end sub
C# example: private void PrepareExample()
{
MySqlCommand cmd = new MySqlCommand("INSERT INTO mytable VALUES (?val)", myConnection);
cmd.Parameters.Add( "?val", 10 );
cmd.Prepare();
cmd.ExecuteNonQuery();
cmd.Parameters[0].Value = 20;
cmd.ExecuteNonQuery();
}
Executes the query, and returns the first column of the first row in the result set returned by the query. Extra columns or rows are ignored. Returns: The first column of the first row in the result set, or a null reference if the result set is empty
Use the
A typical C# example: cmd.CommandText = "select count(*) from region"; Int32 count = (int32) cmd.ExecuteScalar(); Examples
The following example creates a
Visual Basic example: Public Sub CreateMySqlCommand(myScalarQuery As String, myConnection As MySqlConnection)
Dim myCommand As New MySqlCommand(myScalarQuery, myConnection)
myCommand.Connection.Open()
myCommand.ExecuteScalar()
myConnection.Close()
End Sub
C# example: public void CreateMySqlCommand(string myScalarQuery, MySqlConnection myConnection)
{
MySqlCommand myCommand = new MySqlCommand(myScalarQuery, myConnection);
myCommand.Connection.Open();
myCommand.ExecuteScalar();
myConnection.Close();
}
C++ example: public:
void CreateMySqlCommand(String* myScalarQuery, MySqlConnection* myConnection)
{
MySqlCommand* myCommand = new MySqlCommand(myScalarQuery, myConnection);
myCommand->Connection->Open();
myCommand->ExecuteScalar();
myConnection->Close();
}
Gets or sets the SQL statement to execute at the data source. Value: The SQL statement or stored procedure to execute. The default is an empty string.
When the Examples
The following example creates a
Visual Basic example: Public Sub CreateMySqlCommand()
Dim myCommand As New MySqlCommand()
myCommand.CommandText = "SELECT * FROM Mytable ORDER BY id"
myCommand.CommandType = CommandType.Text
End Sub
C# example: public void CreateMySqlCommand()
{
MySqlCommand myCommand = new MySqlCommand();
myCommand.CommandText = "SELECT * FROM mytable ORDER BY id";
myCommand.CommandType = CommandType.Text;
}
Gets or sets the wait time before terminating the attempt to execute a command and generating an error. Value: The time (in seconds) to wait for the command to execute. The default is 0 seconds. MySQL currently does not support any method of canceling a pending or executing operation. All commands issued against a MySQL server will execute until completion or until an exception occurs. MySQL Enterprise MySQL Enterprise subscribers will find more information about CommandTimeout in the Knowledge Base article, Why CommandTimeout is not Supported. Access to the MySQL Knowledge Base collection of articles is one of the advantages of subscribing to MySQL Enterprise. For more information see http://www.mysql.com/products/enterprise/advisors.html.
Gets or sets a value indicating how the
Value: One of the
When you set the Examples
The following example creates a
Visual Basic example: Public Sub CreateMySqlCommand()
Dim myCommand As New MySqlCommand()
myCommand.CommandType = CommandType.Text
End Sub
C# example: public void CreateMySqlCommand()
{
MySqlCommand myCommand = new MySqlCommand();
myCommand.CommandType = CommandType.Text;
}
Gets or sets the
Value: The connection to a
data source. The default value is a null reference
(
If you set Examples
The following example creates a
Visual Basic example: Public Sub CreateMySqlCommand()
Dim mySelectQuery As String = "SELECT * FROM mytable ORDER BY id"
Dim myConnectString As String = "Persist Security Info=False;database=test;server=myServer"
Dim myCommand As New MySqlCommand(mySelectQuery)
myCommand.Connection = New MySqlConnection(myConnectString)
myCommand.CommandType = CommandType.Text
End Sub
C# example: public void CreateMySqlCommand()
{
string mySelectQuery = "SELECT * FROM mytable ORDER BY id";
string myConnectString = "Persist Security Info=False;database=test;server=myServer";
MySqlCommand myCommand = new MySqlCommand(mySelectQuery);
myCommand.Connection = new MySqlConnection(myConnectString);
myCommand.CommandType = CommandType.Text;
}
Get the Value: The parameters of the SQL statement or stored procedure. The default is an empty collection. Connector/Net does not support unnamed parameters. Every parameter added to the collection must have an associated name. Examples
The following example creates a
Visual Basic example: Public Sub CreateMySqlCommand(myConnection As MySqlConnection, _
mySelectQuery As String, myParamArray() As MySqlParameter)
Dim myCommand As New MySqlCommand(mySelectQuery, myConnection)
myCommand.CommandText = "SELECT id, name FROM mytable WHERE age=?age"
myCommand.UpdatedRowSource = UpdateRowSource.Both
myCommand.Parameters.Add(myParamArray)
Dim j As Integer
For j = 0 To myCommand.Parameters.Count - 1
myCommand.Parameters.Add(myParamArray(j))
Next j
Dim myMessage As String = ""
Dim i As Integer
For i = 0 To myCommand.Parameters.Count - 1
myMessage += myCommand.Parameters(i).ToString() & ControlChars.Cr
Next i
Console.WriteLine(myMessage)
End Sub
C# example: public void CreateMySqlCommand(MySqlConnection myConnection, string mySelectQuery,
MySqlParameter[] myParamArray)
{
MySqlCommand myCommand = new MySqlCommand(mySelectQuery, myConnection);
myCommand.CommandText = "SELECT id, name FROM mytable WHERE age=?age";
myCommand.Parameters.Add(myParamArray);
for (int j=0; j<myParamArray.Length; j++)
{
myCommand.Parameters.Add(myParamArray[j]) ;
}
string myMessage = "";
for (int i = 0; i < myCommand.Parameters.Count; i++)
{
myMessage += myCommand.Parameters[i].ToString() + "\n";
}
MessageBox.Show(myMessage);
}
Gets or sets the
Value: The
You cannot set the
Gets or sets how command results are applied to the
Value: One of the
The default
Automatically generates single-table commands used to reconcile changes made to a DataSet with the associated MySQL database. This class cannot be inherited.
The
The
To generate INSERT, UPDATE, or DELETE statements, the
The
The
If you call Note
Caution must be used when using
Examples
The following example uses the Visual Basic example: Public Shared Function SelectRows(myConnection As String, mySelectQuery As String, myTableName As String) As DataSet
Dim myConn As New MySqlConnection(myConnection)
Dim myDataAdapter As New MySqlDataAdapter()
myDataAdapter.SelectCommand = New MySqlCommand(mySelectQuery, myConn)
Dim cb As SqlCommandBuilder = New MySqlCommandBuilder(myDataAdapter)
myConn.Open()
Dim ds As DataSet = New DataSet
myDataAdapter.Fill(ds, myTableName)
' Code to modify data in DataSet here
' Without the MySqlCommandBuilder this line would fail.
myDataAdapter.Update(ds, myTableName)
myConn.Close()
End Function 'SelectRows
C# example: public static DataSet SelectRows(string myConnection, string mySelectQuery, string myTableName)
{
MySqlConnection myConn = new MySqlConnection(myConnection);
MySqlDataAdapter myDataAdapter = new MySqlDataAdapter();
myDataAdapter.SelectCommand = new MySqlCommand(mySelectQuery, myConn);
MySqlCommandBuilder cb = new MySqlCommandBuilder(myDataAdapter);
myConn.Open();
DataSet ds = new DataSet();
myDataAdapter.Fill(ds, myTableName);
//code to modify data in DataSet here
//Without the MySqlCommandBuilder this line would fail
myDataAdapter.Update(ds, myTableName);
myConn.Close();
return ds;
}
Initializes a new instance of the
Initializes a new instance of the
Parameters: False to generate change protection code. True otherwise.
The
Initializes a new instance of the
Parameters: The
The
When you create a new instance
Initializes a new instance of the
Parameters: The
Parameters: False to generate change protection code. True otherwise.
The
When you create a new instance
The
Gets or sets a
Value: A
The
When you create a new instance
Gets or sets the beginning character or characters to use when specifying MySQL database objects (for example, tables or columns) whose names contain characters such as spaces or reserved tokens. Value: The beginning character or characters to use. The default value is `.
Database objects in MySQL can contain special characters such
as spaces that would make normal SQL strings impossible to
correctly parse. Use of the Gets or sets the beginning character or characters to use when specifying MySQL database objects (for example, tables or columns) whose names contain characters such as spaces or reserved tokens. Value: The beginning character or characters to use. The default value is `.
Database objects in MySQL can contain special characters such
as spaces that would make normal SQL strings impossible to
correctly parse. Use of the
Gets the automatically generated
Returns: The
An application can use the
You can also use
After the SQL statement is first generated, the application
must explicitly call
Gets the automatically generated
Returns: The
An application can use the
You can also use the
After the SQL statement is first generated, the application
must explicitly call
Gets the automatically generated
Returns: The
An application can use the
You can also use
After the SQL statement is first generated, the application
must explicitly call Refreshes the database schema information used to generate INSERT, UPDATE, or DELETE statements.
An application should call
An application should call MySQL Enterprise MySQL Enterprise subscribers will find more information on this topic in the Knowledge Base article, Understanding MySqlCommandBuilder and the LastOneWins Setting . For information about subscribing to MySQL Enterprise see http://www.mysql.com/products/enterprise/advisors.html.
Represents an open connection to a MySQL Server database. This class cannot be inherited.
A
If the Examples
The following example creates a Visual Basic example: Public Sub InsertRow(myConnectionString As String)
' If the connection string is null, use a default.
If myConnectionString = "" Then
myConnectionString = "Database=Test;Data Source=localhost;User Id=username;Password=pass"
End If
Dim myConnection As New MySqlConnection(myConnectionString)
Dim myInsertQuery As String = "INSERT INTO Orders (id, customerId, amount) Values(1001, 23, 30.66)"
Dim myCommand As New MySqlCommand(myInsertQuery)
myCommand.Connection = myConnection
myConnection.Open()
myCommand.ExecuteNonQuery()
myCommand.Connection.Close()
End Sub
C# example: public void InsertRow(string myConnectionString)
{
// If the connection string is null, use a default.
if(myConnectionString == "")
{
myConnectionString = "Database=Test;Data Source=localhost;User Id=username;Password=pass";
}
MySqlConnection myConnection = new MySqlConnection(myConnectionString);
string myInsertQuery = "INSERT INTO Orders (id, customerId, amount) Values(1001, 23, 30.66)";
MySqlCommand myCommand = new MySqlCommand(myInsertQuery);
myCommand.Connection = myConnection;
myConnection.Open();
myCommand.ExecuteNonQuery();
myCommand.Connection.Close();
}
Initializes a new instance of the
When a new instance of
You can change the value for these properties only by using
the Examples Overload methods for MySqlConnection
Initializes a new instance of the
Initializes a new instance of the
When a new instance of
You can change the value for these properties only by using
the Examples Parameters: The connection properties used to open the MySQL database. Opens a database connection with the property settings specified by the ConnectionString. Exception: Cannot open a connection without specifying a data source or server. Exception: A connection-level error occurred while opening the connection.
The Examples
The following example creates a
Visual Basic example: Public Sub CreateMySqlConnection(myConnString As String)
Dim myConnection As New MySqlConnection(myConnString)
myConnection.Open()
MessageBox.Show("ServerVersion: " + myConnection.ServerVersion _
+ ControlChars.Cr + "State: " + myConnection.State.ToString())
myConnection.Close()
End Sub
C# example: public void CreateMySqlConnection(string myConnString)
{
MySqlConnection myConnection = new MySqlConnection(myConnString);
myConnection.Open();
MessageBox.Show("ServerVersion: " + myConnection.ServerVersion +
"\nState: " + myConnection.State.ToString());
myConnection.Close();
}
Gets the name of the current database or the database to be used after a connection is opened. Returns: The name of the current database or the name of the database to be used after a connection is opened. The default value is an empty string.
The Examples
The following example creates a
Visual Basic example: Public Sub CreateMySqlConnection()
Dim myConnString As String = _
"Persist Security Info=False;database=test;server=localhost;user id=joeuser;pwd=pass"
Dim myConnection As New MySqlConnection( myConnString )
myConnection.Open()
MessageBox.Show( "Server Version: " + myConnection.ServerVersion _
+ ControlChars.NewLine + "Database: " + myConnection.Database )
myConnection.ChangeDatabase( "test2" )
MessageBox.Show( "ServerVersion: " + myConnection.ServerVersion _
+ ControlChars.NewLine + "Database: " + myConnection.Database )
myConnection.Close()
End Sub
C# example: public void CreateMySqlConnection()
{
string myConnString =
"Persist Security Info=False;database=test;server=localhost;user id=joeuser;pwd=pass";
MySqlConnection myConnection = new MySqlConnection( myConnString );
myConnection.Open();
MessageBox.Show( "Server Version: " + myConnection.ServerVersion
+ "\nDatabase: " + myConnection.Database );
myConnection.ChangeDatabase( "test2" );
MessageBox.Show( "ServerVersion: " + myConnection.ServerVersion
+ "\nDatabase: " + myConnection.Database );
myConnection.Close();
}
Gets the current state of the connection.
Returns: A bitwise
combination of the
The allowed state changes are:
Examples
The following example creates a
Visual Basic example: Public Sub CreateMySqlConnection(myConnString As String)
Dim myConnection As New MySqlConnection(myConnString)
myConnection.Open()
MessageBox.Show("ServerVersion: " + myConnection.ServerVersion _
+ ControlChars.Cr + "State: " + myConnection.State.ToString())
myConnection.Close()
End Sub
C# example: public void CreateMySqlConnection(string myConnString)
{
MySqlConnection myConnection = new MySqlConnection(myConnString);
myConnection.Open();
MessageBox.Show("ServerVersion: " + myConnection.ServerVersion +
"\nState: " + myConnection.State.ToString());
myConnection.Close();
}
Gets a string containing the version of the MySQL server to which the client is connected. Returns: The version of the instance of MySQL. Exception: The connection is closed. Examples
The following example creates a
Visual Basic example: Public Sub CreateMySqlConnection(myConnString As String)
Dim myConnection As New MySqlConnection(myConnString)
myConnection.Open()
MessageBox.Show("ServerVersion: " + myConnection.ServerVersion _
+ ControlChars.Cr + "State: " + myConnection.State.ToString())
myConnection.Close()
End Sub
C# example: public void CreateMySqlConnection(string myConnString)
{
MySqlConnection myConnection = new MySqlConnection(myConnString);
myConnection.Open();
MessageBox.Show("ServerVersion: " + myConnection.ServerVersion +
"\nState: " + myConnection.State.ToString());
myConnection.Close();
}
Closes the connection to the database. This is the preferred method of closing any open connection.
The
An application can call Examples
The following example creates a
Visual Basic example: Public Sub CreateMySqlConnection(myConnString As String)
Dim myConnection As New MySqlConnection(myConnString)
myConnection.Open()
MessageBox.Show("ServerVersion: " + myConnection.ServerVersion _
+ ControlChars.Cr + "State: " + myConnection.State.ToString())
myConnection.Close()
End Sub
C# example: public void CreateMySqlConnection(string myConnString)
{
MySqlConnection myConnection = new MySqlConnection(myConnString);
myConnection.Open();
MessageBox.Show("ServerVersion: " + myConnection.ServerVersion +
"\nState: " + myConnection.State.ToString());
myConnection.Close();
}
Creates and returns a
Returns: A
Begins a database transaction. Returns: An object representing the new transaction. Exception: Parallel transactions are not supported. This command is equivalent to the MySQL BEGIN TRANSACTION command.
You must explicitly commit or roll back the transaction using
the Note
If you do not specify an isolation level, the default
isolation level is used. To specify an isolation level with
the Examples
The following example creates a
Visual Basic example: Public Sub RunTransaction(myConnString As String)
Dim myConnection As New MySqlConnection(myConnString)
myConnection.Open()
Dim myCommand As MySqlCommand = myConnection.CreateCommand()
Dim myTrans As MySqlTransaction
' Start a local transaction
myTrans = myConnection.BeginTransaction()
' Must assign both transaction object and connection
' to Command object for a pending local transaction
myCommand.Connection = myConnection
myCommand.Transaction = myTrans
Try
myCommand.CommandText = "Insert into Test (id, desc) VALUES (100, 'Description')"
myCommand.ExecuteNonQuery()
myCommand.CommandText = "Insert into Test (id, desc) VALUES (101, 'Description')"
myCommand.ExecuteNonQuery()
myTrans.Commit()
Console.WriteLine("Both records are written to database.")
Catch e As Exception
Try
myTrans.Rollback()
Catch ex As MySqlException
If Not myTrans.Connection Is Nothing Then
Console.WriteLine("An exception of type " + ex.GetType().ToString() + _
" was encountered while attempting to roll back the transaction.")
End If
End Try
Console.WriteLine("An exception of type " + e.GetType().ToString() + _
"was encountered while inserting the data.")
Console.WriteLine("Neither record was written to database.")
Finally
myConnection.Close()
End Try
End Sub
C# example: public void RunTransaction(string myConnString)
{
MySqlConnection myConnection = new MySqlConnection(myConnString);
myConnection.Open();
MySqlCommand myCommand = myConnection.CreateCommand();
MySqlTransaction myTrans;
// Start a local transaction
myTrans = myConnection.BeginTransaction();
// Must assign both transaction object and connection
// to Command object for a pending local transaction
myCommand.Connection = myConnection;
myCommand.Transaction = myTrans;
try
{
myCommand.CommandText = "insert into Test (id, desc) VALUES (100, 'Description')";
myCommand.ExecuteNonQuery();
myCommand.CommandText = "insert into Test (id, desc) VALUES (101, 'Description')";
myCommand.ExecuteNonQuery();
myTrans.Commit();
Console.WriteLine("Both records are written to database.");
}
catch(Exception e)
{
try
{
myTrans.Rollback();
}
catch (SqlException ex)
{
if (myTrans.Connection != null)
{
Console.WriteLine("An exception of type " + ex.GetType() +
" was encountered while attempting to roll back the transaction.");
}
}
Console.WriteLine("An exception of type " + e.GetType() +
" was encountered while inserting the data.");
Console.WriteLine("Neither record was written to database.");
}
finally
{
myConnection.Close();
}
}
Begins a database transaction with the specified isolation level. Parameters: The isolation level under which the transaction should run. Returns: An object representing the new transaction. Exception: Parallel exceptions are not supported. This command is equivalent to the MySQL BEGIN TRANSACTION command.
You must explicitly commit or roll back the transaction using
the Note
If you do not specify an isolation level, the default
isolation level is used. To specify an isolation level with
the Examples
The following example creates a
Visual Basic example: Public Sub RunTransaction(myConnString As String)
Dim myConnection As New MySqlConnection(myConnString)
myConnection.Open()
Dim myCommand As MySqlCommand = myConnection.CreateCommand()
Dim myTrans As MySqlTransaction
' Start a local transaction
myTrans = myConnection.BeginTransaction()
' Must assign both transaction object and connection
' to Command object for a pending local transaction
myCommand.Connection = myConnection
myCommand.Transaction = myTrans
Try
myCommand.CommandText = "Insert into Test (id, desc) VALUES (100, 'Description')"
myCommand.ExecuteNonQuery()
myCommand.CommandText = "Insert into Test (id, desc) VALUES (101, 'Description')"
myCommand.ExecuteNonQuery()
myTrans.Commit()
Console.WriteLine("Both records are written to database.")
Catch e As Exception
Try
myTrans.Rollback()
Catch ex As MySqlException
If Not myTrans.Connection Is Nothing Then
Console.WriteLine("An exception of type " + ex.GetType().ToString() + _
" was encountered while attempting to roll back the transaction.")
End If
End Try
Console.WriteLine("An exception of type " + e.GetType().ToString() + _
"was encountered while inserting the data.")
Console.WriteLine("Neither record was written to database.")
Finally
myConnection.Close()
End Try
End Sub
C# example: public void RunTransaction(string myConnString)
{
MySqlConnection myConnection = new MySqlConnection(myConnString);
myConnection.Open();
MySqlCommand myCommand = myConnection.CreateCommand();
MySqlTransaction myTrans;
// Start a local transaction
myTrans = myConnection.BeginTransaction();
// Must assign both transaction object and connection
// to Command object for a pending local transaction
myCommand.Connection = myConnection;
myCommand.Transaction = myTrans;
try
{
myCommand.CommandText = "insert into Test (id, desc) VALUES (100, 'Description')";
myCommand.ExecuteNonQuery();
myCommand.CommandText = "insert into Test (id, desc) VALUES (101, 'Description')";
myCommand.ExecuteNonQuery();
myTrans.Commit();
Console.WriteLine("Both records are written to database.");
}
catch(Exception e)
{
try
{
myTrans.Rollback();
}
catch (SqlException ex)
{
if (myTrans.Connection != null)
{
Console.WriteLine("An exception of type " + ex.GetType() +
" was encountered while attempting to roll back the transaction.");
}
}
Console.WriteLine("An exception of type " + e.GetType() +
" was encountered while inserting the data.");
Console.WriteLine("Neither record was written to database.");
}
finally
{
myConnection.Close();
}
}
Changes the current database for an open MySqlConnection. Parameters: The name of the database to use.
The value supplied in the When you are using connection pooling against MySQL, and you close the connection, it is returned to the connection pool. The next time the connection is retrieved from the pool, the reset connection request executes before the user performs any operations. MySQL Enterprise MySQL Enterprise subscribers will find more information on this subject in the Knowledge Base article, Understanding and Using Connection Pooling. Access to the MySQL Knowledge Base collection of articles is one of the advantages of subscribing to MySQL Enterprise. To subscribe see http://www.mysql.com/products/enterprise/advisors.html. Exception: The database name is not valid. Exception: The connection is not open. Exception: Cannot change the database. Examples
The following example creates a
Visual Basic example: Public Sub CreateMySqlConnection()
Dim myConnString As String = _
"Persist Security Info=False;database=test;server=localhost;user id=joeuser;pwd=pass"
Dim myConnection As New MySqlConnection( myConnString )
myConnection.Open()
MessageBox.Show( "Server Version: " + myConnection.ServerVersion _
+ ControlChars.NewLine + "Database: " + myConnection.Database )
myConnection.ChangeDatabase( "test2" )
MessageBox.Show( "ServerVersion: " + myConnection.ServerVersion _
+ ControlChars.NewLine + "Database: " + myConnection.Database )
myConnection.Close()
End Sub
C# example: public void CreateMySqlConnection()
{
string myConnString =
"Persist Security Info=False;database=test;server=localhost;user id=joeuser;pwd=pass";
MySqlConnection myConnection = new MySqlConnection( myConnString );
myConnection.Open();
MessageBox.Show( "Server Version: " + myConnection.ServerVersion
+ "\nDatabase: " + myConnection.Database );
myConnection.ChangeDatabase( "test2" );
MessageBox.Show( "ServerVersion: " + myConnection.ServerVersion
+ "\nDatabase: " + myConnection.Database );
myConnection.Close();
}
Occurs when the state of the connection changes.
The
If an event handler throws an exception from within the
The
The event handler receives an argument of type
Occurs when MySQL returns warnings as a result of executing a command or query. Gets the time to wait while trying to establish a connection before terminating the attempt and generating an error. Exception: The value set is less than 0.
A value of 0 indicates no limit, and should be avoided in a
Examples The following example creates a MySqlConnection and sets some of its properties in the connection string. Visual Basic example: Public Sub CreateSqlConnection() Dim myConnection As New MySqlConnection() myConnection.ConnectionString = "Persist Security Info=False;Username=user;Password=pass;database=test1;server=localhost;Connect Timeout=30" myConnection.Open() End Sub C# example: public void CreateSqlConnection()
{
MySqlConnection myConnection = new MySqlConnection();
myConnection.ConnectionString = "Persist Security Info=False;Username=user;»
Password=pass;database=test1;server=localhost;Connect Timeout=30";
myConnection.Open();
}
Gets or sets the string used to connect to a MySQL Server database.
The
You can use the "Persist Security Info=False;database=MyDB;»
server=MySqlServer;user id=myUser;Password=myPass"
The To connect to a local machine, specify "localhost" for the server. If you do not specify a server, localhost is assumed.
Resetting the
The connection string is parsed immediately after being set.
If errors in syntax are found when parsing, a runtime
exception, such as
The basic format of a connection string consists of a series
of keyword/value pairs separated by semicolons. The equal sign
(
The following table lists the valid names for keyword values
within the
The following table lists the valid names for connection
pooling values within the
When setting keyword or connection pooling values that require a Boolean value, you can use 'yes' instead of 'true', and 'no' instead of 'false'.
Examples
The following example creates a
Visual Basic example: Public Sub CreateConnection()
Dim myConnection As New MySqlConnection()
myConnection.ConnectionString = "Persist Security Info=False;database=myDB;server=myHost;Connect Timeout=30;user id=myUser; pwd=myPass"
myConnection.Open()
End Sub 'CreateConnection
C# example: public void CreateConnection()
{
MySqlConnection myConnection = new MySqlConnection();
myConnection.ConnectionString = "Persist Security Info=False;database=myDB;server=myHost;Connect Timeout=30;user id=myUser; pwd=myPass";
myConnection.Open();
}
Examples
The following example creates a
Visual Basic example: Public Sub CreateConnection()
Dim myConnection As New MySqlConnection()
myConnection.ConnectionString = "database=myDB;server=/var/lib/mysql/mysql.sock;user id=myUser; pwd=myPass"
myConnection.Open()
End Sub 'CreateConnection
C# example: public void CreateConnection()
{
MySqlConnection myConnection = new MySqlConnection();
myConnection.ConnectionString = "database=myDB;server=/var/lib/mysql/mysql.sock;user id=myUser; pwd=myPass";
myConnection.Open();
}
Represents a set of data commands and a database connection that are used to fill a dataset and update a MySQL database. This class cannot be inherited.
The
When the
The
When an instance of Note
Please be aware that the Examples
The following example creates a Visual Basic example: Public Function SelectRows(dataSet As DataSet, connection As String, query As String) As DataSet
Dim conn As New MySqlConnection(connection)
Dim adapter As New MySqlDataAdapter()
adapter.SelectCommand = new MySqlCommand(query, conn)
adapter.Fill(dataset)
Return dataset
End Function
C# example: public DataSet SelectRows(DataSet dataset,string connection,string query)
{
MySqlConnection conn = new MySqlConnection(connection);
MySqlDataAdapter adapter = new MySqlDataAdapter();
adapter.SelectCommand = new MySqlCommand(query, conn);
adapter.Fill(dataset);
return dataset;
}
Overload methods for MySqlDataAdapter Initializes a new instance of the MySqlDataAdapter class.
When an instance of
You can change the value of any of these properties through a separate call to the property. Examples
The following example creates a
Visual Basic example:
Public Sub CreateSqlDataAdapter()
Dim conn As MySqlConnection = New MySqlConnection("Data Source=localhost;" & _
"database=test")
Dim da As MySqlDataAdapter = New MySqlDataAdapter
da.MissingSchemaAction = MissingSchemaAction.AddWithKey
da.SelectCommand = New MySqlCommand("SELECT id, name FROM mytable", conn)
da.InsertCommand = New MySqlCommand("INSERT INTO mytable (id, name) " & _
"VALUES (?id, ?name)", conn)
da.UpdateCommand = New MySqlCommand("UPDATE mytable SET id=?id, name=?name " & _
"WHERE id=?oldId", conn)
da.DeleteCommand = New MySqlCommand("DELETE FROM mytable WHERE id=?id", conn)
da.InsertCommand.Parameters.Add("?id", MySqlDbType.VarChar, 5, "id")
da.InsertCommand.Parameters.Add("?name", MySqlDbType.VarChar, 40, "name")
da.UpdateCommand.Parameters.Add("?id", MySqlDbType.VarChar, 5, "id")
da.UpdateCommand.Parameters.Add("?name", MySqlDbType.VarChar, 40, "name")
da.UpdateCommand.Parameters.Add("?oldId", MySqlDbType.VarChar, 5, "id").SourceVersion = DataRowVersion.Original
da.DeleteCommand.Parameters.Add("?id", MySqlDbType.VarChar, 5, "id").SourceVersion = DataRowVersion.Original
End Sub
C# example: public static void CreateSqlDataAdapter()
{
MySqlConnection conn = new MySqlConnection("Data Source=localhost;database=test");
MySqlDataAdapter da = new MySqlDataAdapter();
da.MissingSchemaAction = MissingSchemaAction.AddWithKey;
da.SelectCommand = new MySqlCommand("SELECT id, name FROM mytable", conn);
da.InsertCommand = new MySqlCommand("INSERT INTO mytable (id, name) " +
"VALUES (?id, ?name)", conn);
da.UpdateCommand = new MySqlCommand("UPDATE mytable SET id=?id, name=?name " +
"WHERE id=?oldId", conn);
da.DeleteCommand = new MySqlCommand("DELETE FROM mytable WHERE id=?id", conn);
da.InsertCommand.Parameters.Add("?id", MySqlDbType.VarChar, 5, "id");
da.InsertCommand.Parameters.Add("?name", MySqlDbType.VarChar, 40, "name");
da.UpdateCommand.Parameters.Add("?id", MySqlDbType.VarChar, 5, "id");
da.UpdateCommand.Parameters.Add("?name", MySqlDbType.VarChar, 40, "name");
da.UpdateCommand.Parameters.Add("?oldId", MySqlDbType.VarChar, 5, "id").SourceVersion = DataRowVersion.Original;
da.DeleteCommand.Parameters.Add("?id", MySqlDbType.VarChar, 5, "id").SourceVersion = DataRowVersion.Original;
}
Initializes a new instance of the
Parameters:
When an instance of
You can change the value of any of these properties through a separate call to the property.
When Examples
The following example creates a
Visual Basic example:
Public Sub CreateSqlDataAdapter()
Dim conn As MySqlConnection = New MySqlConnection("Data Source=localhost;" & _
"database=test")
Dim cmd as new MySqlCommand("SELECT id, name FROM mytable", conn)
Dim da As MySqlDataAdapter = New MySqlDataAdapter(cmd)
da.MissingSchemaAction = MissingSchemaAction.AddWithKey
da.InsertCommand = New MySqlCommand("INSERT INTO mytable (id, name) " & _
"VALUES (?id, ?name)", conn)
da.UpdateCommand = New MySqlCommand("UPDATE mytable SET id=?id, name=?name " & _
"WHERE id=?oldId", conn)
da.DeleteCommand = New MySqlCommand("DELETE FROM mytable WHERE id=?id", conn)
da.InsertCommand.Parameters.Add("?id", MySqlDbType.VarChar, 5, "id")
da.InsertCommand.Parameters.Add("?name", MySqlDbType.VarChar, 40, "name")
da.UpdateCommand.Parameters.Add("?id", MySqlDbType.VarChar, 5, "id")
da.UpdateCommand.Parameters.Add("?name", MySqlDbType.VarChar, 40, "name")
da.UpdateCommand.Parameters.Add("?oldId", MySqlDbType.VarChar, 5, "id").SourceVersion = DataRowVersion.Original
da.DeleteCommand.Parameters.Add("?id", MySqlDbType.VarChar, 5, "id").SourceVersion = DataRowVersion.Original
End Sub
C# example: public static void CreateSqlDataAdapter()
{
MySqlConnection conn = new MySqlConnection("Data Source=localhost;database=test");
MySqlCommand cmd = new MySqlCommand("SELECT id, name FROM mytable", conn);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.MissingSchemaAction = MissingSchemaAction.AddWithKey;
da.InsertCommand = new MySqlCommand("INSERT INTO mytable (id, name) " +
"VALUES (?id, ?name)", conn);
da.UpdateCommand = new MySqlCommand("UPDATE mytable SET id=?id, name=?name " +
"WHERE id=?oldId", conn);
da.DeleteCommand = new MySqlCommand("DELETE FROM mytable WHERE id=?id", conn);
da.InsertCommand.Parameters.Add("?id", MySqlDbType.VarChar, 5, "id");
da.InsertCommand.Parameters.Add("?name", MySqlDbType.VarChar, 40, "name");
da.UpdateCommand.Parameters.Add("?id", MySqlDbType.VarChar, 5, "id");
da.UpdateCommand.Parameters.Add("?name", MySqlDbType.VarChar, 40, "name");
da.UpdateCommand.Parameters.Add("?oldId", MySqlDbType.VarChar, 5, "id").SourceVersion = DataRowVersion.Original;
da.DeleteCommand.Parameters.Add("?id", MySqlDbType.VarChar, 5, "id").SourceVersion = DataRowVersion.Original;
}
Initializes a new instance of the
Parameters: A
Parameters: A
This implementation of the
When an instance of
You can change the value of any of these properties through a separate call to the property. Examples
The following example creates a
Visual Basic example:
Public Sub CreateSqlDataAdapter()
Dim conn As MySqlConnection = New MySqlConnection("Data Source=localhost;" & _
"database=test")
Dim da As MySqlDataAdapter = New MySqlDataAdapter("SELECT id, name FROM mytable", conn)
da.MissingSchemaAction = MissingSchemaAction.AddWithKey
da.InsertCommand = New MySqlCommand("INSERT INTO mytable (id, name) " & _
"VALUES (?id, ?name)", conn)
da.UpdateCommand = New MySqlCommand("UPDATE mytable SET id=?id, name=?name " & _
"WHERE id=?oldId", conn)
da.DeleteCommand = New MySqlCommand("DELETE FROM mytable WHERE id=?id", conn)
da.InsertCommand.Parameters.Add("?id", MySqlDbType.VarChar, 5, "id")
da.InsertCommand.Parameters.Add("?name", MySqlDbType.VarChar, 40, "name")
da.UpdateCommand.Parameters.Add("?id", MySqlDbType.VarChar, 5, "id")
da.UpdateCommand.Parameters.Add("?name", MySqlDbType.VarChar, 40, "name")
da.UpdateCommand.Parameters.Add("?oldId", MySqlDbType.VarChar, 5, "id").SourceVersion = DataRowVersion.Original
da.DeleteCommand.Parameters.Add("?id", MySqlDbType.VarChar, 5, "id").SourceVersion = DataRowVersion.Original
End Sub
C# example: public static void CreateSqlDataAdapter()
{
MySqlConnection conn = new MySqlConnection("Data Source=localhost;database=test");
MySqlDataAdapter da = new MySqlDataAdapter("SELECT id, name FROM mytable", conn);
da.MissingSchemaAction = MissingSchemaAction.AddWithKey;
da.InsertCommand = new MySqlCommand("INSERT INTO mytable (id, name) " +
"VALUES (?id, ?name)", conn);
da.UpdateCommand = new MySqlCommand("UPDATE mytable SET id=?id, name=?name " +
"WHERE id=?oldId", conn);
da.DeleteCommand = new MySqlCommand("DELETE FROM mytable WHERE id=?id", conn);
da.InsertCommand.Parameters.Add("?id", MySqlDbType.VarChar, 5, "id");
da.InsertCommand.Parameters.Add("?name", MySqlDbType.VarChar, 40, "name");
da.UpdateCommand.Parameters.Add("?id", MySqlDbType.VarChar, 5, "id");
da.UpdateCommand.Parameters.Add("?name", MySqlDbType.VarChar, 40, "name");
da.UpdateCommand.Parameters.Add("?oldId", MySqlDbType.VarChar, 5, "id").SourceVersion = DataRowVersion.Original;
da.DeleteCommand.Parameters.Add("?id", MySqlDbType.VarChar, 5, "id").SourceVersion = DataRowVersion.Original;
}
Initializes a new instance of the
Parameters: A
Parameters: The connection string
When an instance of
You can change the value of any of these properties through a separate call to the property. Examples
The following example creates a
Visual Basic example:
Public Sub CreateSqlDataAdapter()
Dim da As MySqlDataAdapter = New MySqlDataAdapter("SELECT id, name FROM mytable", "Data Source=localhost;database=test")
Dim conn As MySqlConnection = da.SelectCommand.Connection
da.MissingSchemaAction = MissingSchemaAction.AddWithKey
da.InsertCommand = New MySqlCommand("INSERT INTO mytable (id, name) " & _
"VALUES (?id, ?name)", conn)
da.UpdateCommand = New MySqlCommand("UPDATE mytable SET id=?id, name=?name " & _
"WHERE id=?oldId", conn)
da.DeleteCommand = New MySqlCommand("DELETE FROM mytable WHERE id=?id", conn)
da.InsertCommand.Parameters.Add("?id", MySqlDbType.VarChar, 5, "id")
da.InsertCommand.Parameters.Add("?name", MySqlDbType.VarChar, 40, "name")
da.UpdateCommand.Parameters.Add("?id", MySqlDbType.VarChar, 5, "id")
da.UpdateCommand.Parameters.Add("?name", MySqlDbType.VarChar, 40, "name")
da.UpdateCommand.Parameters.Add("?oldId", MySqlDbType.VarChar, 5, "id").SourceVersion = DataRowVersion.Original
da.DeleteCommand.Parameters.Add("?id", MySqlDbType.VarChar, 5, "id").SourceVersion = DataRowVersion.Original
End Sub
C# example: public static void CreateSqlDataAdapter()
{
MySqlDataAdapter da = new MySqlDataAdapter("SELECT id, name FROM mytable", "Data Source=localhost;database=test");
MySqlConnection conn = da.SelectCommand.Connection;
da.MissingSchemaAction = MissingSchemaAction.AddWithKey;
da.InsertCommand = new MySqlCommand("INSERT INTO mytable (id, name) " +
"VALUES (?id, ?name)", conn);
da.UpdateCommand = new MySqlCommand("UPDATE mytable SET id=?id, name=?name " +
"WHERE id=?oldId", conn);
da.DeleteCommand = new MySqlCommand("DELETE FROM mytable WHERE id=?id", conn);
da.InsertCommand.Parameters.Add("?id", MySqlDbType.VarChar, 5, "id");
da.InsertCommand.Parameters.Add("?name", MySqlDbType.VarChar, 40, "name");
da.UpdateCommand.Parameters.Add("?id", MySqlDbType.VarChar, 5, "id");
da.UpdateCommand.Parameters.Add("?name", MySqlDbType.VarChar, 40, "name");
da.UpdateCommand.Parameters.Add("?oldId", MySqlDbType.VarChar, 5, "id").SourceVersion = DataRowVersion.Original;
da.DeleteCommand.Parameters.Add("?id", MySqlDbType.VarChar, 5, "id").SourceVersion = DataRowVersion.Original;
}
Gets or sets a SQL statement or stored procedure used to delete records from the data set.
Value: A
During
When Examples
The following example creates a
Visual Basic example: Public Shared Function CreateCustomerAdapter(conn As MySqlConnection) As MySqlDataAdapter
Dim da As MySqlDataAdapter = New MySqlDataAdapter()
Dim cmd As MySqlCommand
Dim parm As MySqlParameter
' Create the SelectCommand.
cmd = New MySqlCommand("SELECT * FROM mytable WHERE id=?id AND name=?name", conn)
cmd.Parameters.Add("?id", MySqlDbType.VarChar, 15)
cmd.Parameters.Add("?name", MySqlDbType.VarChar, 15)
da.SelectCommand = cmd
' Create the DeleteCommand.
cmd = New MySqlCommand("DELETE FROM mytable WHERE id=?id", conn)
parm = cmd.Parameters.Add("?id", MySqlDbType.VarChar, 5, "id")
parm.SourceVersion = DataRowVersion.Original
da.DeleteCommand = cmd
Return da
End Function
C# example: public static MySqlDataAdapter CreateCustomerAdapter(MySqlConnection conn)
{
MySqlDataAdapter da = new MySqlDataAdapter();
MySqlCommand cmd;
MySqlParameter parm;
// Create the SelectCommand.
cmd = new MySqlCommand("SELECT * FROM mytable WHERE id=?id AND name=?name", conn);
cmd.Parameters.Add("?id", MySqlDbType.VarChar, 15);
cmd.Parameters.Add("?name", MySqlDbType.VarChar, 15);
da.SelectCommand = cmd;
// Create the DeleteCommand.
cmd = new MySqlCommand("DELETE FROM mytable WHERE id=?id", conn);
parm = cmd.Parameters.Add("?id", MySqlDbType.VarChar, 5, "id");
parm.SourceVersion = DataRowVersion.Original;
da.DeleteCommand = cmd;
return da;
}
Gets or sets a SQL statement or stored procedure used to insert records into the data set.
Value: A
During
When Note
If execution of this command returns rows, these rows may be
added to the Examples
The following example creates a
Visual Basic example: Public Shared Function CreateCustomerAdapter(conn As MySqlConnection) As MySqlDataAdapter
Dim da As MySqlDataAdapter = New MySqlDataAdapter()
Dim cmd As MySqlCommand
Dim parm As MySqlParameter
' Create the SelectCommand.
cmd = New MySqlCommand("SELECT * FROM mytable WHERE id=?id AND name=?name", conn)
cmd.Parameters.Add("?id", MySqlDbType.VarChar, 15)
cmd.Parameters.Add("?name", MySqlDbType.VarChar, 15)
da.SelectCommand = cmd
' Create the InsertCommand.
cmd = New MySqlCommand("INSERT INTO mytable (id,name) VALUES (?id, ?name)", conn)
cmd.Parameters.Add( "?id", MySqlDbType.VarChar, 15, "id" )
cmd.Parameters.Add( "?name", MySqlDbType.VarChar, 15, "name" )
da.InsertCommand = cmd
Return da
End Function
C# example: public static MySqlDataAdapter CreateCustomerAdapter(MySqlConnection conn)
{
MySqlDataAdapter da = new MySqlDataAdapter();
MySqlCommand cmd;
MySqlParameter parm;
// Create the SelectCommand.
cmd = new MySqlCommand("SELECT * FROM mytable WHERE id=?id AND name=?name", conn);
cmd.Parameters.Add("?id", MySqlDbType.VarChar, 15);
cmd.Parameters.Add("?name", MySqlDbType.VarChar, 15);
da.SelectCommand = cmd;
// Create the InsertCommand.
cmd = new MySqlCommand("INSERT INTO mytable (id,name) VALUES (?id,?name)", conn);
cmd.Parameters.Add("?id", MySqlDbType.VarChar, 15, "id" );
cmd.Parameters.Add("?name", MySqlDbType.VarChar, 15, "name" );
da.InsertCommand = cmd;
return da;
}
Gets or sets a SQL statement or stored procedure used to updated records in the data source.
Value: A
During
When Note
If execution of this command returns rows, these rows may be
merged with the DataSet depending on how you set the
Examples
The following example creates a
Visual Basic example: Public Shared Function CreateCustomerAdapter(conn As MySqlConnection) As MySqlDataAdapter
Dim da As MySqlDataAdapter = New MySqlDataAdapter()
Dim cmd As MySqlCommand
Dim parm As MySqlParameter
' Create the SelectCommand.
cmd = New MySqlCommand("SELECT * FROM mytable WHERE id=?id AND name=?name", conn)
cmd.Parameters.Add("?id", MySqlDbType.VarChar, 15)
cmd.Parameters.Add("?name", MySqlDbType.VarChar, 15)
da.SelectCommand = cmd
' Create the UpdateCommand.
cmd = New MySqlCommand("UPDATE mytable SET id=?id, name=?name WHERE id=?oldId", conn)
cmd.Parameters.Add( "?id", MySqlDbType.VarChar, 15, "id" )
cmd.Parameters.Add( "?name", MySqlDbType.VarChar, 15, "name" )
parm = cmd.Parameters.Add("?oldId", MySqlDbType.VarChar, 15, "id")
parm.SourceVersion = DataRowVersion.Original
da.UpdateCommand = cmd
Return da
End Function
C# example: public static MySqlDataAdapter CreateCustomerAdapter(MySqlConnection conn)
{
MySqlDataAdapter da = new MySqlDataAdapter();
MySqlCommand cmd;
MySqlParameter parm;
// Create the SelectCommand.
cmd = new MySqlCommand("SELECT * FROM mytable WHERE id=?id AND name=?name", conn);
cmd.Parameters.Add("?id", MySqlDbType.VarChar, 15);
cmd.Parameters.Add("?name", MySqlDbType.VarChar, 15);
da.SelectCommand = cmd;
// Create the UpdateCommand.
cmd = new MySqlCommand("UPDATE mytable SET id=?id, name=?name WHERE id=?oldId", conn);
cmd.Parameters.Add("?id", MySqlDbType.VarChar, 15, "id" );
cmd.Parameters.Add("?name", MySqlDbType.VarChar, 15, "name" );
parm = cmd.Parameters.Add( "?oldId", MySqlDbType.VarChar, 15, "id" );
parm.SourceVersion = DataRowVersion.Original;
da.UpdateCommand = cmd;
return da;
}
Gets or sets a SQL statement or stored procedure used to select records in the data source.
Value: A
When
If the Examples
The following example creates a
Visual Basic example: Public Shared Function CreateCustomerAdapter(conn As MySqlConnection) As MySqlDataAdapter
Dim da As MySqlDataAdapter = New MySqlDataAdapter()
Dim cmd As MySqlCommand
Dim parm As MySqlParameter
' Create the SelectCommand.
cmd = New MySqlCommand("SELECT * FROM mytable WHERE id=?id AND name=?name", conn)
cmd.Parameters.Add("?id", MySqlDbType.VarChar, 15)
cmd.Parameters.Add("?name", MySqlDbType.VarChar, 15)
da.SelectCommand = cmd
' Create the InsertCommand.
cmd = New MySqlCommand("INSERT INTO mytable (id,name) VALUES (?id, ?name)", conn)
cmd.Parameters.Add( "?id", MySqlDbType.VarChar, 15, "id" )
cmd.Parameters.Add( "?name", MySqlDbType.VarChar, 15, "name" )
da.InsertCommand = cmd
Return da
End Function
C# example: public static MySqlDataAdapter CreateCustomerAdapter(MySqlConnection conn)
{
MySqlDataAdapter da = new MySqlDataAdapter();
MySqlCommand cmd;
MySqlParameter parm;
// Create the SelectCommand.
cmd = new MySqlCommand("SELECT * FROM mytable WHERE id=?id AND name=?name", conn);
cmd.Parameters.Add("?id", MySqlDbType.VarChar, 15);
cmd.Parameters.Add("?name", MySqlDbType.VarChar, 15);
da.SelectCommand = cmd;
// Create the InsertCommand.
cmd = new MySqlCommand("INSERT INTO mytable (id,name) VALUES (?id,?name)", conn);
cmd.Parameters.Add("?id", MySqlDbType.VarChar, 15, "id" );
cmd.Parameters.Add("?name", MySqlDbType.VarChar, 15, "name" );
da.InsertCommand = cmd;
return da;
}
To create a
While the
For optimal performance, Examples
The following example creates a
Visual Basic example: Public Sub ReadMyData(myConnString As String)
Dim mySelectQuery As String = "SELECT OrderID, CustomerID FROM Orders"
Dim myConnection As New MySqlConnection(myConnString)
Dim myCommand As New MySqlCommand(mySelectQuery, myConnection)
myConnection.Open()
Dim myReader As MySqlDataReader
myReader = myCommand.ExecuteReader()
' Always call Read before accessing data.
While myReader.Read()
Console.WriteLine((myReader.GetInt32(0) & ", " & myReader.GetString(1)))
End While
' always call Close when done reading.
myReader.Close()
' Close the connection when done with it.
myConnection.Close()
End Sub 'ReadMyData
C# example: public void ReadMyData(string myConnString) {
string mySelectQuery = "SELECT OrderID, CustomerID FROM Orders";
MySqlConnection myConnection = new MySqlConnection(myConnString);
MySqlCommand myCommand = new MySqlCommand(mySelectQuery,myConnection);
myConnection.Open();
MySqlDataReader myReader;
myReader = myCommand.ExecuteReader();
// Always call Read before accessing data.
while (myReader.Read()) {
Console.WriteLine(myReader.GetInt32(0) + ", " + myReader.GetString(1));
}
// always call Close when done reading.
myReader.Close();
// Close the connection when done with it.
myConnection.Close();
}
If you pass a buffer that is a null reference
( No conversions are performed; therefore the data retrieved must already be a byte array.
Gets the value of the specified column as a
Parameters: The zero-based column ordinal. Returns: The value of the specified column.
Gets the value of the specified column as a
Note
MySQL allows date columns to contain the value '0000-00-00'
and datetime columns to contain the value '0000-00-00
00:00:00'. The DateTime structure cannot contain or
represent these values. To read a datetime value from a
column that might contain zero values, use
Parameters: The zero-based column ordinal. Returns: The value of the specified column.
Gets the value of the specified column as a
Parameters: The zero-based column ordinal. Returns: The value of the specified column.
Gets the value of the specified column as a
Parameters: The zero-based column ordinal. Returns: The value of the specified column.
Gets the value of the specified column as a
Parameters: The zero-based column ordinal. Returns: The value of the specified column. Gets the value of the specified column as a double-precision floating point number. Parameters: The zero-based column ordinal. Returns: The value of the specified column. Gets the value of the specified column as a single-precision floating point number. Parameters: The zero-based column ordinal. Returns: The value of the specified column. Gets the value of the specified column as a globally-unique identifier (GUID). Parameters: The zero-based column ordinal. Returns: The value of the specified column. Gets the value of the specified column as a 16-bit signed integer. Parameters: The zero-based column ordinal. Returns: The value of the specified column. Gets the value of the specified column as a 32-bit signed integer. Parameters: The zero-based column ordinal. Returns: The value of the specified column. Gets the value of the specified column as a 64-bit signed integer. Parameters: The zero-based column ordinal. Returns: The value of the specified column. Gets the value of the specified column as a 16-bit unsigned integer. Parameters: The zero-based column ordinal. Returns: The value of the specified column. Gets the value of the specified column as a 32-bit unsigned integer. Parameters: The zero-based column ordinal. Returns: The value of the specified column. This class is created whenever the MySQL Data Provider encounters an error generated from the server.
Any open connections are not automatically closed when an
exception is thrown. If the client application determines that
the exception is fatal, it should close any open
Examples
The following example generates a
Visual Basic example: Public Sub ShowException()
Dim mySelectQuery As String = "SELECT column1 FROM table1"
Dim myConnection As New MySqlConnection ("Data Source=localhost;Database=Sample;")
Dim myCommand As New MySqlCommand(mySelectQuery, myConnection)
Try
myCommand.Connection.Open()
Catch e As MySqlException
MessageBox.Show( e.Message )
End Try
End Sub
C# example: public void ShowException()
{
string mySelectQuery = "SELECT column1 FROM table1";
MySqlConnection myConnection =
new MySqlConnection("Data Source=localhost;Database=Sample;");
MySqlCommand myCommand = new MySqlCommand(mySelectQuery,myConnection);
try
{
myCommand.Connection.Open();
}
catch (MySqlException e)
{
MessageBox.Show( e.Message );
}
}
Parameter names are not case sensitive. Examples
The following example creates multiple instances of
Visual Basic example: Public Sub AddSqlParameters()
' ...
' create myDataSet and myDataAdapter
' ...
myDataAdapter.SelectCommand.Parameters.Add("@CategoryName", MySqlDbType.VarChar, 80).Value = "toasters"
myDataAdapter.SelectCommand.Parameters.Add("@SerialNum", MySqlDbType.Long).Value = 239
myDataAdapter.Fill(myDataSet)
End Sub 'AddSqlParameters
C# example: public void AddSqlParameters()
{
// ...
// create myDataSet and myDataAdapter
// ...
myDataAdapter.SelectCommand.Parameters.Add("@CategoryName", MySqlDbType.VarChar, 80).Value = "toasters";
myDataAdapter.SelectCommand.Parameters.Add("@SerialNum", MySqlDbType.Long).Value = 239;
myDataAdapter.Fill(myDataSet);
}
The number of the parameters in the collection must be equal to the number of parameter placeholders within the command text, or an exception will be generated. Examples
The following example creates multiple instances of
Visual Basic example: Public Sub AddParameters()
' ...
' create myDataSet and myDataAdapter
' ...
myDataAdapter.SelectCommand.Parameters.Add("@CategoryName", MySqlDbType.VarChar, 80).Value = "toasters"
myDataAdapter.SelectCommand.Parameters.Add("@SerialNum", MySqlDbType.Long).Value = 239
myDataAdapter.Fill(myDataSet)
End Sub 'AddSqlParameters
C# example: public void AddSqlParameters()
{
// ...
// create myDataSet and myDataAdapter
// ...
myDataAdapter.SelectCommand.Parameters.Add("@CategoryName", MySqlDbType.VarChar, 80).Value = "toasters";
myDataAdapter.SelectCommand.Parameters.Add("@SerialNum", MySqlDbType.Long).Value = 239;
myDataAdapter.Fill(myDataSet);
}
Represents a SQL transaction to be made in a MySQL database. This class cannot be inherited.
The application creates a Examples
The following example creates a
Visual Basic example: Public Sub RunTransaction(myConnString As String)
Dim myConnection As New MySqlConnection(myConnString)
myConnection.Open()
Dim myCommand As MySqlCommand = myConnection.CreateCommand()
Dim myTrans As MySqlTransaction
' Start a local transaction
myTrans = myConnection.BeginTransaction()
' Must assign both transaction object and connection
' to Command object for a pending local transaction
myCommand.Connection = myConnection
myCommand.Transaction = myTrans
Try
myCommand.CommandText = "Insert into Region (RegionID, RegionDescription) VALUES (100, 'Description')"
myCommand.ExecuteNonQuery()
myCommand.CommandText = "Insert into Region (RegionID, RegionDescription) VALUES (101, 'Description')"
myCommand.ExecuteNonQuery()
myTrans.Commit()
Console.WriteLine("Both records are written to database.")
Catch e As Exception
Try
myTrans.Rollback()
Catch ex As MySqlException
If Not myTrans.Connection Is Nothing Then
Console.WriteLine("An exception of type " & ex.GetType().ToString() & _
" was encountered while attempting to roll back the transaction.")
End If
End Try
Console.WriteLine("An exception of type " & e.GetType().ToString() & _
"was encountered while inserting the data.")
Console.WriteLine("Neither record was written to database.")
Finally
myConnection.Close()
End Try
End Sub 'RunTransaction
C# example: public void RunTransaction(string myConnString)
{
MySqlConnection myConnection = new MySqlConnection(myConnString);
myConnection.Open();
MySqlCommand myCommand = myConnection.CreateCommand();
MySqlTransaction myTrans;
// Start a local transaction
myTrans = myConnection.BeginTransaction();
// Must assign both transaction object and connection
// to Command object for a pending local transaction
myCommand.Connection = myConnection;
myCommand.Transaction = myTrans;
try
{
myCommand.CommandText = "Insert into Region (RegionID, RegionDescription) VALUES (100, 'Description')";
myCommand.ExecuteNonQuery();
myCommand.CommandText = "Insert into Region (RegionID, RegionDescription) VALUES (101, 'Description')";
myCommand.ExecuteNonQuery();
myTrans.Commit();
Console.WriteLine("Both records are written to database.");
}
catch(Exception e)
{
try
{
myTrans.Rollback();
}
catch (MySqlException ex)
{
if (myTrans.Connection != null)
{
Console.WriteLine("An exception of type " + ex.GetType() +
" was encountered while attempting to roll back the transaction.");
}
}
Console.WriteLine("An exception of type " + e.GetType() +
" was encountered while inserting the data.");
Console.WriteLine("Neither record was written to database.");
}
finally
{
myConnection.Close();
}
}
Rolls back a transaction from a pending state. The Rollback method is equivalent to the MySQL statement ROLLBACK. The transaction can only be rolled back from a pending state (after BeginTransaction has been called, but before Commit is called). Examples
The following example creates
Visual Basic example: Public Sub RunSqlTransaction(myConnString As String)
Dim myConnection As New MySqlConnection(myConnString)
myConnection.Open()
Dim myCommand As MySqlCommand = myConnection.CreateCommand()
Dim myTrans As MySqlTransaction
' Start a local transaction
myTrans = myConnection.BeginTransaction()
' Must assign both transaction object and connection
' to Command object for a pending local transaction
myCommand.Connection = myConnection
myCommand.Transaction = myTrans
Try
myCommand.CommandText = "Insert into mytable (id, desc) VALUES (100, 'Description')"
myCommand.ExecuteNonQuery()
myCommand.CommandText = "Insert into mytable (id, desc) VALUES (101, 'Description')"
myCommand.ExecuteNonQuery()
myTrans.Commit()
Console.WriteLine("Success.")
Catch e As Exception
Try
myTrans.Rollback()
Catch ex As MySqlException
If Not myTrans.Connection Is Nothing Then
Console.WriteLine("An exception of type " & ex.GetType().ToString() & _
" was encountered while attempting to roll back the transaction.")
End If
End Try
Console.WriteLine("An exception of type " & e.GetType().ToString() & _
"was encountered while inserting the data.")
Console.WriteLine("Neither record was written to database.")
Finally
myConnection.Close()
End Try
End Sub
C# example: public void RunSqlTransaction(string myConnString)
{
MySqlConnection myConnection = new MySqlConnection(myConnString);
myConnection.Open();
MySqlCommand myCommand = myConnection.CreateCommand();
MySqlTransaction myTrans;
// Start a local transaction
myTrans = myConnection.BeginTransaction();
// Must assign both transaction object and connection
// to Command object for a pending local transaction
myCommand.Connection = myConnection;
myCommand.Transaction = myTrans;
try
{
myCommand.CommandText = "Insert into mytable (id, desc) VALUES (100, 'Description')";
myCommand.ExecuteNonQuery();
myCommand.CommandText = "Insert into mytable (id, desc) VALUES (101, 'Description')";
myCommand.ExecuteNonQuery();
myTrans.Commit();
Console.WriteLine("Both records are written to database.");
}
catch(Exception e)
{
try
{
myTrans.Rollback();
}
catch (MySqlException ex)
{
if (myTrans.Connection != null)
{
Console.WriteLine("An exception of type " + ex.GetType() +
" was encountered while attempting to roll back the transaction.");
}
}
Console.WriteLine("An exception of type " + e.GetType() +
" was encountered while inserting the data.");
Console.WriteLine("Neither record was written to database.");
}
finally
{
myConnection.Close();
}
}
Commits the database transaction.
The Examples
The following example creates
Visual Basic example: Public Sub RunSqlTransaction(myConnString As String)
Dim myConnection As New MySqlConnection(myConnString)
myConnection.Open()
Dim myCommand As MySqlCommand = myConnection.CreateCommand()
Dim myTrans As MySqlTransaction
' Start a local transaction
myTrans = myConnection.BeginTransaction()
' Must assign both transaction object and connection
' to Command object for a pending local transaction
myCommand.Connection = myConnection
myCommand.Transaction = myTrans
Try
myCommand.CommandText = "Insert into mytable (id, desc) VALUES (100, 'Description')"
myCommand.ExecuteNonQuery()
myCommand.CommandText = "Insert into mytable (id, desc) VALUES (101, 'Description')"
myCommand.ExecuteNonQuery()
myTrans.Commit()
Console.WriteLine("Success.")
Catch e As Exception
Try
myTrans.Rollback()
Catch ex As MySqlException
If Not myTrans.Connection Is Nothing Then
Console.WriteLine("An exception of type " & ex.GetType().ToString() & _
" was encountered while attempting to roll back the transaction.")
End If
End Try
Console.WriteLine("An exception of type " & e.GetType().ToString() & _
"was encountered while inserting the data.")
Console.WriteLine("Neither record was written to database.")
Finally
myConnection.Close()
End Try
End Sub
C# example: public void RunSqlTransaction(string myConnString)
{
MySqlConnection myConnection = new MySqlConnection(myConnString);
myConnection.Open();
MySqlCommand myCommand = myConnection.CreateCommand();
MySqlTransaction myTrans;
// Start a local transaction
myTrans = myConnection.BeginTransaction();
// Must assign both transaction object and connection
// to Command object for a pending local transaction
myCommand.Connection = myConnection;
myCommand.Transaction = myTrans;
try
{
myCommand.CommandText = "Insert into mytable (id, desc) VALUES (100, 'Description')";
myCommand.ExecuteNonQuery();
myCommand.CommandText = "Insert into mytable (id, desc) VALUES (101, 'Description')";
myCommand.ExecuteNonQuery();
myTrans.Commit();
Console.WriteLine("Both records are written to database.");
}
catch(Exception e)
{
try
{
myTrans.Rollback();
}
catch (MySqlException ex)
{
if (myTrans.Connection != null)
{
Console.WriteLine("An exception of type " + ex.GetType() +
" was encountered while attempting to roll back the transaction.");
}
}
Console.WriteLine("An exception of type " + e.GetType() +
" was encountered while inserting the data.");
Console.WriteLine("Neither record was written to database.");
}
finally
{
myConnection.Close();
}
}
This section of the manual contains a complete reference to the Connector/NET ADO.NET component, automatically generated from the embedded documentation. Classes
Delegates
Enumerations
For a list of all members of this type, see MySqlCommand Members . Syntax: Visual Basic NotInheritable Public Class MySqlCommand_ Inherits Component_ Implements IDbCommand, ICloneable Syntax: C# public sealed class MySqlCommand : Component, IDbCommand, ICloneable Thread Safety Public static (Shared in Visual Basic) members of this type are safe for multithreaded operations. Instance members are not guaranteed to be thread-safe. Requirements Namespace: MySql.Data.MySqlClient Assembly: MySql.Data (in MySql.Data.dll) See Also MySqlCommand Members , MySql.Data.MySqlClient Namespace
Public Instance Constructors
Public Instance Properties
Public Instance Methods
Public Instance Events
See Also MySqlCommand Class , MySql.Data.MySqlClient Namespace Initializes a new instance of the MySqlCommand class. Overload List Initializes a new instance of the MySqlCommand class. See Also MySqlCommand Class , MySql.Data.MySqlClient Namespace Initializes a new instance of the MySqlCommand class. Syntax: Visual Basic Overloads Public Sub New() Syntax: C# public MySqlCommand(); See Also MySqlCommand Class , MySql.Data.MySqlClient Namespace , MySqlCommand Constructor Overload List Syntax: Visual Basic Overloads Public Sub New( _ ByVal cmdText As String _ ) Syntax: C# public MySqlCommand( stringcmdText ); See Also MySqlCommand Class , MySql.Data.MySqlClient Namespace , MySqlCommand Constructor Overload List Syntax: Visual Basic Overloads Public Sub New( _ ByVal cmdText As String, _ ByVal connection As MySqlConnection _ ) Syntax: C# public MySqlCommand( stringcmdText, MySqlConnectionconnection ); See Also MySqlCommand Class , MySql.Data.MySqlClient Namespace , MySqlCommand Constructor Overload List For a list of all members of this type, see MySqlConnection Members . Syntax: Visual Basic NotInheritable Public Class MySqlConnection_ Inherits Component_ Implements IDbConnection, ICloneable Syntax: C# public sealed class MySqlConnection : Component, IDbConnection, ICloneable Thread Safety Public static (Shared in Visual Basic) members of this type are safe for multithreaded operations. Instance members are not guaranteed to be thread-safe. Requirements Namespace: MySql.Data.MySqlClient Assembly: MySql.Data (in MySql.Data.dll) See Also MySqlConnection Members , MySql.Data.MySqlClient Namespace Public Instance Constructors
Public Instance Properties
Public Instance Methods
Public Instance Events
See Also MySqlConnection Class , MySql.Data.MySqlClient Namespace Initializes a new instance of the MySqlConnection class. Overload List Initializes a new instance of the MySqlConnection class. See Also MySqlConnection Class , MySql.Data.MySqlClient Namespace Initializes a new instance of the MySqlConnection class. Syntax: Visual Basic Overloads Public Sub New() Syntax: C# public MySqlConnection(); See Also MySqlConnection Class , MySql.Data.MySqlClient Namespace , MySqlConnection Constructor Overload List Syntax: Visual Basic Overloads Public Sub New( _ ByVal connectionString As String _ ) Syntax: C# public MySqlConnection( stringconnectionString ); See Also MySqlConnection Class , MySql.Data.MySqlClient Namespace , MySqlConnection Constructor Overload List Syntax: Visual Basic NotOverridable Public Property ConnectionString As String _ _ Implements IDbConnection.ConnectionString Syntax: C# public string ConnectionString {get; set;}
Implements IDbConnection.ConnectionString See Also Syntax: Visual Basic NotOverridable Public ReadOnly Property ConnectionTimeout As Integer _ _ Implements IDbConnection.ConnectionTimeout Syntax: C# public int ConnectionTimeout {get;}
Implements IDbConnection.ConnectionTimeout See Also Syntax: Visual Basic NotOverridable Public ReadOnly Property Database As String _ _ Implements IDbConnection.Database Syntax: C# public string Database {get;}
Implements IDbConnection.Database See Also Gets the name of the MySQL server to which to connect. Syntax: Visual Basic Public ReadOnly Property DataSource As String Syntax: C# public string DataSource {get;}See Also Returns the id of the server thread this connection is executing on Syntax: Visual Basic Public ReadOnly Property ServerThread As Integer Syntax: C# public int ServerThread {get;}See Also Syntax: Visual Basic Public ReadOnly Property ServerVersion As String Syntax: C# public string ServerVersion {get;}See Also Syntax: Visual Basic NotOverridable Public ReadOnly Property State As ConnectionState _ _ Implements IDbConnection.State Syntax: C# public System.Data.ConnectionState State {get;}
Implements IDbConnection.State See Also Indicates if this connection should use compression when communicating with the server. Syntax: Visual Basic Public ReadOnly Property UseCompression As Boolean Syntax: C# public bool UseCompression {get;}See Also Overload List See Also MySqlConnection Class , MySql.Data.MySqlClient Namespace Syntax: Visual Basic Overloads Public Function BeginTransaction() As MySqlTransaction Syntax: C# public MySqlTransaction BeginTransaction(); See Also MySqlConnection Class , MySql.Data.MySqlClient Namespace , MySqlConnection.BeginTransaction Overload List For a list of all members of this type, see MySqlTransaction Members . Syntax: Visual Basic NotInheritable Public Class MySqlTransaction_ Implements IDbTransaction, IDisposable Syntax: C# public sealed class MySqlTransaction : IDbTransaction, IDisposable Thread Safety Public static (Sharedin Visual Basic) members of this type are safe for multithreaded operations. Instance members are notguaranteed to be thread-safe. Requirements Namespace: MySql.Data.MySqlClient Assembly: MySql.Data (in MySql.Data.dll) See Also MySqlTransaction Members , MySql.Data.MySqlClient Namespace Public Instance Properties
Public Instance Methods
See Also MySqlTransaction Class , MySql.Data.MySqlClient Namespace Gets the MySqlConnection object associated with the transaction, or a null reference (Nothing in Visual Basic) if the transaction is no longer valid. Syntax: Visual Basic Public ReadOnly Property Connection As MySqlConnection Syntax: C# public MySqlConnection Connection {get;}Property Value The MySqlConnection object associated with this transaction. Remarks A single application may have multiple database connections, each with zero or more transactions. This property enables you to determine the connection object associated with a particular transaction created by BeginTransaction . See Also Specifies the IsolationLevelfor this transaction. Syntax: Visual Basic NotOverridable Public ReadOnly Property IsolationLevel As IsolationLevel _ _ Implements IDbTransaction.IsolationLevel Syntax: C# public System.Data.IsolationLevel IsolationLevel {get;}
Property Value The IsolationLevel for this transaction. The default is ReadCommitted. Implements IDbTransaction.IsolationLevel Remarks Parallel transactions are not supported. Therefore, the IsolationLevel applies to the entire transaction. See Also Syntax: Visual Basic NotOverridable Public Sub Commit() _ _ Implements IDbTransaction.Commit Syntax: C# public void Commit(); Implements IDbTransaction.Commit See Also Syntax: Visual Basic NotOverridable Public Sub Rollback() _ _ Implements IDbTransaction.Rollback Syntax: C# public void Rollback(); Implements IDbTransaction.Rollback See Also Syntax: Visual Basic Overloads Public Function BeginTransaction( _ ByVal iso As IsolationLevel _ ) As MySqlTransaction Syntax: C# public MySqlTransaction BeginTransaction( IsolationLeveliso ); See Also MySqlConnection Class , MySql.Data.MySqlClient Namespace , MySqlConnection.BeginTransaction Overload List Syntax: Visual Basic NotOverridable Public Sub ChangeDatabase( _ ByVal databaseName As String _ ) _ _ Implements IDbConnection.ChangeDatabase Syntax: C# public void ChangeDatabase( stringdatabaseName ); Implements IDbConnection.ChangeDatabase See Also Syntax: Visual Basic NotOverridable Public Sub Close() _ _ Implements IDbConnection.Close Syntax: C# public void Close(); Implements IDbConnection.Close See Also Syntax: Visual Basic Public Function CreateCommand() As MySqlCommand Syntax: C# public MySqlCommand CreateCommand(); See Also Syntax: Visual Basic NotOverridable Public Sub Open() _ _ Implements IDbConnection.Open Syntax: C# public void Open(); Implements IDbConnection.Open See Also Ping Syntax: Visual Basic Public Function Ping() As Boolean Syntax: C# public bool Ping(); Return Value See Also Syntax: Visual Basic Public Event InfoMessage As MySqlInfoMessageEventHandler Syntax: C# public event MySqlInfoMessageEventHandler InfoMessage; See Also MySqlConnection Class , MySql.Data.MySqlClient Namespace Represents the method that will handle the InfoMessage event of a MySqlConnection . Syntax: Visual Basic Public Delegate Sub MySqlInfoMessageEventHandler( _ ByVal sender As Object, _ ByVal args As MySqlInfoMessageEventArgs _ ) Syntax: C# public delegate void MySqlInfoMessageEventHandler( objectsender, MySqlInfoMessageEventArgsargs ); Requirements Namespace: MySql.Data.MySqlClient Assembly: MySql.Data (in MySql.Data.dll) See Also MySql.Data.MySqlClient Namespace Provides data for the InfoMessage event. This class cannot be inherited. For a list of all members of this type, see MySqlInfoMessageEventArgs Members . Syntax: Visual Basic Public Class MySqlInfoMessageEventArgs_ Inherits EventArgs Syntax: C# public class MySqlInfoMessageEventArgs : EventArgs Thread Safety Public static (Sharedin Visual Basic) members of this type are safe for multithreaded operations. Instance members are notguaranteed to be thread-safe. Requirements Namespace: MySql.Data.MySqlClient Assembly: MySql.Data (in MySql.Data.dll) See Also MySqlInfoMessageEventArgs Members , MySql.Data.MySqlClient Namespace MySqlInfoMessageEventArgs overview Public Instance Constructors
Public Instance Fields Public Instance Methods
Protected Instance Methods
See Also MySqlInfoMessageEventArgs Class , MySql.Data.MySqlClient Namespace Initializes a new instance of the MySqlInfoMessageEventArgs class. Syntax: Visual Basic Public Sub New() Syntax: C# public MySqlInfoMessageEventArgs(); See Also MySqlInfoMessageEventArgs Class , MySql.Data.MySqlClient Namespace Syntax: Visual Basic Public errors As MySqlError() Syntax: C# public MySqlError[] errors; See Also MySqlInfoMessageEventArgs Class , MySql.Data.MySqlClient Namespace Collection of error codes that can be returned by the server For a list of all members of this type, see MySqlError Members . Syntax: Visual Basic Public Class MySqlError Syntax: C# public class MySqlError Thread Safety Public static (Shared in Visual Basic) members of this type are safe for multithreaded operations. Instance members are not guaranteed to be thread-safe. Requirements Namespace: MySql.Data.MySqlClient Assembly: MySql.Data (in MySql.Data.dll) See Also MySqlError Members , MySql.Data.MySqlClient Namespace Public Instance Constructors Public Instance Properties Public Instance Methods
Protected Instance Methods
See Also MySqlError Class , MySql.Data.MySqlClient Namespace Syntax: Visual Basic Public Sub New( _ ByVal level As String, _ ByVal code As Integer, _ ByVal message As String _ ) Syntax: C# public MySqlError( stringlevel, intcode, stringmessage ); Parameters
See Also Error code Syntax: Visual Basic Public ReadOnly Property Code As Integer Syntax: C# public int Code {get;}See Also Error level Syntax: Visual Basic Public ReadOnly Property Level As String Syntax: C# public string Level {get;}See Also Error message Syntax: Visual Basic Public ReadOnly Property Message As String Syntax: C# public string Message {get;}See Also Syntax: Visual Basic Public Event StateChange As StateChangeEventHandler Syntax: C# public event StateChangeEventHandler StateChange; See Also Syntax: Visual Basic Overloads Public Sub New( _ ByVal cmdText As String, _ ByVal connection As MySqlConnection, _ ByVal transaction As MySqlTransaction _ ) Syntax: C# public MySqlCommand( stringcmdText, MySqlConnectionconnection, MySqlTransactiontransaction ); See Also MySqlCommand Class , MySql.Data.MySqlClient Namespace , MySqlCommand Constructor Overload List Syntax: Visual Basic NotOverridable Public Property CommandText As String _ _ Implements IDbCommand.CommandText Syntax: C# public string CommandText {get; set;}
Implements IDbCommand.CommandText See Also Syntax: Visual Basic NotOverridable Public Property CommandTimeout As Integer _ _ Implements IDbCommand.CommandTimeout Syntax: C# public int CommandTimeout {get; set;}
Implements IDbCommand.CommandTimeout See Also Syntax: Visual Basic NotOverridable Public Property CommandType As CommandType _ _ Implements IDbCommand.CommandType Syntax: C# public System.Data.CommandType CommandType {get; set;}
Implements IDbCommand.CommandType See Also Syntax: Visual Basic Public Property Connection As MySqlConnection Syntax: C# public MySqlConnection Connection {get; set;}See Also Syntax: Visual Basic Public ReadOnly Property IsPrepared As Boolean Syntax: C# public bool IsPrepared {get;}See Also Syntax: Visual Basic Public ReadOnly Property Parameters As MySqlParameterCollection Syntax: C# public MySqlParameterCollection Parameters {get;}See Also MySqlCommand Class , MySql.Data.MySqlClient Namespace Represents a collection of parameters relevant to a MySqlCommand as well as their respective mappings to columns in a DataSet. This class cannot be inherited. For a list of all members of this type, see MySqlParameterCollection Members . Syntax: Visual Basic NotInheritable Public Class MySqlParameterCollection_ Inherits MarshalByRefObject_ Implements IDataParameterCollection, IList, ICollection, IEnumerable Syntax: C# public sealed class MySqlParameterCollection : MarshalByRefObject, IDataParameterCollection, IList, ICollection, IEnumerable Thread Safety Public static (Shared in Visual Basic) members of this type are safe for multithreaded operations. Instance members are not guaranteed to be thread-safe. Requirements Namespace: MySql.Data.MySqlClient Assembly: MySql.Data (in MySql.Data.dll) See Also MySqlParameterCollection Members , MySql.Data.MySqlClient Namespace
MySqlParameterCollection overview Public Instance Constructors
Public Instance Properties
Public Instance Methods
See Also MySqlParameterCollection Class , MySql.Data.MySqlClient Namespace Initializes a new instance of the MySqlParameterCollection class. Syntax: Visual Basic Public Sub New() Syntax: C# public MySqlParameterCollection(); See Also MySqlParameterCollection Class , MySql.Data.MySqlClient Namespace Gets the number of MySqlParameter objects in the collection. Syntax: Visual Basic NotOverridable Public ReadOnly Property Count As Integer _ _ Implements ICollection.Count Syntax: C# public int Count {get;}
Implements ICollection.Count See Also MySqlParameterCollection Class , MySql.Data.MySqlClient Namespace Gets the MySqlParameter with a specified attribute. In C#, this property is the indexer for the MySqlParameterCollection class. Overload List Gets the MySqlParameter at the specified index. Gets the MySqlParameter with the specified name. See Also MySqlParameterCollection Class , MySql.Data.MySqlClient Namespace Represents a parameter to a MySqlCommand , and optionally, its mapping to DataSetcolumns. This class cannot be inherited. For a list of all members of this type, see MySqlParameter Members . Syntax: Visual Basic NotInheritable Public Class MySqlParameter_ Inherits MarshalByRefObject_ Implements IDataParameter, IDbDataParameter, ICloneable Syntax: C# public sealed class MySqlParameter : MarshalByRefObject, IDataParameter, IDbDataParameter, ICloneable Thread Safety Public static (Shared in Visual Basic) members of this type are safe for multithreaded operations. Instance members are not guaranteed to be thread-safe. Requirements Namespace: MySql.Data.MySqlClient Assembly: MySql.Data (in MySql.Data.dll) See Also MySqlParameter Members , MySql.Data.MySqlClient Namespace Public Instance Constructors
Public Instance Properties
Public Instance Methods
See Also MySqlParameter Class , MySql.Data.MySqlClient Namespace Initializes a new instance of the MySqlParameter class. Overload List Initializes a new instance of the MySqlParameter class. Initializes a new instance of the MySqlParameter class with the parameter name and the data type. Initializes a new instance of the MySqlParameter class with the parameter name, the MySqlDbType , and the size. Initializes a new instance of the MySqlParameter class with the parameter name, the type of the parameter, the size of the parameter, a ParameterDirection, the precision of the parameter, the scale of the parameter, the source column, a DataRowVersionto use, and the value of the parameter. Initializes a new instance of the MySqlParameter class with the parameter name, the MySqlDbType , the size, and the source column name. Initializes a new instance of the MySqlParameter class with the parameter name and a value of the new MySqlParameter. See Also MySqlParameter Class , MySql.Data.MySqlClient Namespace Initializes a new instance of the MySqlParameter class. Syntax: Visual Basic Overloads Public Sub New() Syntax: C# public MySqlParameter(); See Also MySqlParameter Class , MySql.Data.MySqlClient Namespace , MySqlParameter Constructor Overload List Initializes a new instance of the MySqlParameter class with the parameter name and the data type. Syntax: Visual Basic Overloads Public Sub New( _ ByVal parameterName As String, _ ByVal dbType As MySqlDbType _ ) Syntax: C# public MySqlParameter( stringparameterName, MySqlDbTypedbType ); Parameters
See Also MySqlParameter Class , MySql.Data.MySqlClient Namespace , MySqlParameter Constructor Overload List Specifies MySQL specific data type of a field, property, for use in a MySqlParameter . Syntax: Visual Basic Public Enum MySqlDbType Syntax: C# public enum MySqlDbType Members
Requirements Namespace: MySql.Data.MySqlClient Assembly: MySql.Data (in MySql.Data.dll) See Also Initializes a new instance of the MySqlParameter class with the parameter name, the MySqlDbType , and the size. Syntax: Visual Basic Overloads Public Sub New( _ ByVal parameterName As String, _ ByVal dbType As MySqlDbType, _ ByVal size As Integer _ ) Syntax: C# public MySqlParameter( stringparameterName, MySqlDbTypedbType, intsize ); Parameters
See Also MySqlParameter Class , MySql.Data.MySqlClient Namespace , MySqlParameter Constructor Overload List Initializes a new instance of the MySqlParameter class with the parameter name, the type of the parameter, the size of the parameter, a ParameterDirection, the precision of the parameter, the scale of the parameter, the source column, a DataRowVersionto use, and the value of the parameter. Syntax: Visual Basic Overloads Public Sub New( _ ByVal parameterName As String, _ ByVal dbType As MySqlDbType, _ ByVal size As Integer, _ ByVal direction As ParameterDirection, _ ByVal isNullable As Boolean, _ ByVal precision As Byte, _ ByVal scale As Byte, _ ByVal sourceColumn As String, _ ByVal sourceVersion As DataRowVersion, _ ByVal value As Object _ ) Syntax: C# public MySqlParameter( stringparameterName, MySqlDbTypedbType, intsize, ParameterDirectiondirection, boolisNullable, byteprecision, bytescale, stringsourceColumn, DataRowVersionsourceVersion, objectvalue ); Parameters
Exceptions
See Also MySqlParameter Class , MySql.Data.MySqlClient Namespace , MySqlParameter Constructor Overload List Gets or sets the value of the parameter. Syntax: Visual Basic NotOverridable Public Property Value As Object _ _ Implements IDataParameter.Value Syntax: C# public object Value {get; set;}
Implements IDataParameter.Value See Also Initializes a new instance of the MySqlParameter class with the parameter name, the MySqlDbType , the size, and the source column name. Syntax: Visual Basic Overloads Public Sub New( _ ByVal parameterName As String, _ ByVal dbType As MySqlDbType, _ ByVal size As Integer, _ ByVal sourceColumn As String _ ) Syntax: C# public MySqlParameter( stringparameterName, MySqlDbTypedbType, intsize, stringsourceColumn ); Parameters
See Also MySqlParameter Class , MySql.Data.MySqlClient Namespace , MySqlParameter Constructor Overload List Initializes a new instance of the MySqlParameter class with the parameter name and a value of the new MySqlParameter. Syntax: Visual Basic Overloads Public Sub New( _ ByVal parameterName As String, _ ByVal value As Object _ ) Syntax: C# public MySqlParameter( stringparameterName, objectvalue ); Parameters
See Also MySqlParameter Class , MySql.Data.MySqlClient Namespace , MySqlParameter Constructor Overload List Gets or sets the DbTypeof the parameter. Syntax: Visual Basic NotOverridable Public Property DbType As DbType _ _ Implements IDataParameter.DbType Syntax: C# public System.Data.DbType DbType {get; set;}
Implements IDataParameter.DbType See Also Gets or sets a value indicating whether the parameter is input-only, output-only, bidirectional, or a stored procedure return value parameter. As of MySQL version 4.1 and earlier, input-only is the only valid choice. Syntax: Visual Basic NotOverridable Public Property Direction As ParameterDirection _ _ Implements IDataParameter.Direction Syntax: C# public System.Data.ParameterDirection Direction {get; set;}
Implements IDataParameter.Direction See Also Gets or sets a value indicating whether the parameter accepts null values. Syntax: Visual Basic NotOverridable Public Property IsNullable As Boolean _ _ Implements IDataParameter.IsNullable Syntax: C# public bool IsNullable {get; set;}
Implements IDataParameter.IsNullable See Also Syntax: Visual Basic Public Property IsUnsigned As Boolean Syntax: C# public bool IsUnsigned {get; set;}See Also Gets or sets the MySqlDbType of the parameter. Syntax: Visual Basic Public Property MySqlDbType As MySqlDbType Syntax: C# public MySqlDbType MySqlDbType {get; set;}See Also Gets or sets the name of the MySqlParameter. Syntax: Visual Basic NotOverridable Public Property ParameterName As String _ _ Implements IDataParameter.ParameterName Syntax: C# public string ParameterName {get; set;}
Implements IDataParameter.ParameterName See Also Gets or sets the maximum number of digits used to represent the Value property. Syntax: Visual Basic NotOverridable Public Property Precision As Byte _ _ Implements IDbDataParameter.Precision Syntax: C# public byte Precision {get; set;}
Implements IDbDataParameter.Precision See Also Gets or sets the number of decimal places to which Value is resolved. Syntax: Visual Basic NotOverridable Public Property Scale As Byte _ _ Implements IDbDataParameter.Scale Syntax: C# public byte Scale {get; set;}
Implements IDbDataParameter.Scale See Also Gets or sets the maximum size, in bytes, of the data within the column. Syntax: Visual Basic NotOverridable Public Property Size As Integer _ _ Implements IDbDataParameter.Size Syntax: C# public int Size {get; set;}
Implements IDbDataParameter.Size See Also Gets or sets the name of the source column that is mapped to the DataSetand used for loading or returning the Value . Syntax: Visual Basic NotOverridable Public Property SourceColumn As String _ _ Implements IDataParameter.SourceColumn Syntax: C# public string SourceColumn {get; set;}
Implements IDataParameter.SourceColumn See Also Gets or sets the DataRowVersionto use when loading Value . Syntax: Visual Basic NotOverridable Public Property SourceVersion As DataRowVersion _ _ Implements IDataParameter.SourceVersion Syntax: C# public System.Data.DataRowVersion SourceVersion {get; set;}
Implements IDataParameter.SourceVersion See Also Overridden. Gets a string containing the ParameterName . Syntax: Visual Basic Overrides Public Function ToString() As String Syntax: C# public override string ToString(); Return Value See Also Gets the MySqlParameter at the specified index. Syntax: Visual Basic Overloads Public Default Property Item( _ ByVal index As Integer _ ) As MySqlParameter Syntax: C# public MySqlParameter this[
intindex
] {get; set;}See Also MySqlParameterCollection Class , MySql.Data.MySqlClient Namespace , MySqlParameterCollection.Item Overload List Gets the MySqlParameter with the specified name. Syntax: Visual Basic Overloads Public Default Property Item( _ ByVal name As String _ ) As MySqlParameter Syntax: C# public MySqlParameter this[
stringname
] {get; set;}See Also MySqlParameterCollection Class , MySql.Data.MySqlClient Namespace , MySqlParameterCollection.Item Overload List Adds the specified MySqlParameter object to the MySqlParameterCollection . Overload List Adds the specified MySqlParameter object to the MySqlParameterCollection . Adds the specified MySqlParameter object to the MySqlParameterCollection . Adds a MySqlParameter to the MySqlParameterCollection given the parameter name and the data type. Adds a MySqlParameter to the MySqlParameterCollection with the parameter name, the data type, and the column length. Adds a MySqlParameter to the MySqlParameterCollection with the parameter name, the data type, the column length, and the source column name. Adds a MySqlParameter to the MySqlParameterCollection given the specified parameter name and value. See Also MySqlParameterCollection Class , MySql.Data.MySqlClient Namespace Adds the specified MySqlParameter object to the MySqlParameterCollection . Syntax: Visual Basic Overloads Public Function Add( _ ByVal value As MySqlParameter _ ) As MySqlParameter Syntax: C# public MySqlParameter Add( MySqlParametervalue ); Parameters
Return Value The newly added MySqlParameter object. See Also MySqlParameterCollection Class , MySql.Data.MySqlClient Namespace , MySqlParameterCollection.Add Overload List Adds the specified MySqlParameter object to the MySqlParameterCollection . Syntax: Visual Basic NotOverridable Overloads Public Function Add( _ ByVal value As Object _ ) As Integer _ _ Implements IList.Add Syntax: C# public int Add( objectvalue ); Parameters
Return Value The index of the new MySqlParameter object. Implements IList.Add See Also MySqlParameterCollection Class , MySql.Data.MySqlClient Namespace , MySqlParameterCollection.Add Overload List Adds a MySqlParameter to the MySqlParameterCollection given the parameter name and the data type. Syntax: Visual Basic Overloads Public Function Add( _ ByVal parameterName As String, _ ByVal dbType As MySqlDbType _ ) As MySqlParameter Syntax: C# public MySqlParameter Add( stringparameterName, MySqlDbTypedbType ); Parameters
Return Value The newly added MySqlParameter object. See Also MySqlParameterCollection Class , MySql.Data.MySqlClient Namespace , MySqlParameterCollection.Add Overload List Adds a MySqlParameter to the MySqlParameterCollection with the parameter name, the data type, and the column length. Syntax: Visual Basic Overloads Public Function Add( _ ByVal parameterName As String, _ ByVal dbType As MySqlDbType, _ ByVal size As Integer _ ) As MySqlParameter Syntax: C# public MySqlParameter Add( stringparameterName, MySqlDbTypedbType, intsize ); Parameters
Return Value The newly added MySqlParameter object. See Also MySqlParameterCollection Class , MySql.Data.MySqlClient Namespace , MySqlParameterCollection.Add Overload List Adds a MySqlParameter to the MySqlParameterCollection with the parameter name, the data type, the column length, and the source column name. Syntax: Visual Basic Overloads Public Function Add( _ ByVal parameterName As String, _ ByVal dbType As MySqlDbType, _ ByVal size As Integer, _ ByVal sourceColumn As String _ ) As MySqlParameter Syntax: C# public MySqlParameter Add( stringparameterName, MySqlDbTypedbType, intsize, stringsourceColumn ); Parameters
Return Value The newly added MySqlParameter object. See Also MySqlParameterCollection Class , MySql.Data.MySqlClient Namespace , MySqlParameterCollection.Add Overload List Adds a MySqlParameter to the MySqlParameterCollection given the specified parameter name and value. Syntax: Visual Basic Overloads Public Function Add( _ ByVal parameterName As String, _ ByVal value As Object _ ) As MySqlParameter Syntax: C# public MySqlParameter Add( stringparameterName, objectvalue ); Parameters
Return Value The newly added MySqlParameter object. See Also MySqlParameterCollection Class , MySql.Data.MySqlClient Namespace , MySqlParameterCollection.Add Overload List Removes all items from the collection. Syntax: Visual Basic NotOverridable Public Sub Clear() _ _ Implements IList.Clear Syntax: C# public void Clear(); Implements IList.Clear See Also MySqlParameterCollection Class , MySql.Data.MySqlClient Namespace Gets a value indicating whether a MySqlParameter exists in the collection. Overload List Gets a value indicating whether a MySqlParameter exists in the collection. Gets a value indicating whether a MySqlParameter with the specified parameter name exists in the collection. See Also MySqlParameterCollection Class , MySql.Data.MySqlClient Namespace Gets a value indicating whether a MySqlParameter exists in the collection. Syntax: Visual Basic NotOverridable Overloads Public Function Contains( _ ByVal value As Object _ ) As Boolean _ _ Implements IList.Contains Syntax: C# public bool Contains( objectvalue ); Parameters
Return Value true if the collection contains the MySqlParameter object; otherwise, false. Implements IList.Contains See Also MySqlParameterCollection Class , MySql.Data.MySqlClient Namespace , MySqlParameterCollection.Contains Overload List Gets a value indicating whether a MySqlParameter with the specified parameter name exists in the collection. Syntax: Visual Basic NotOverridable Overloads Public Function Contains( _ ByVal name As String _ ) As Boolean _ _ Implements IDataParameterCollection.Contains Syntax: C# public bool Contains( stringname ); Parameters
Return Value true if the collection contains the parameter; otherwise, false. Implements IDataParameterCollection.Contains See Also MySqlParameterCollection Class , MySql.Data.MySqlClient Namespace , MySqlParameterCollection.Contains Overload List Copies MySqlParameter objects from the MySqlParameterCollection to the specified array. Syntax: Visual Basic NotOverridable Public Sub CopyTo( _ ByVal array As Array, _ ByVal index As Integer _ ) _ _ Implements ICollection.CopyTo Syntax: C# public void CopyTo( Arrayarray, intindex ); Parameters
Implements ICollection.CopyTo See Also MySqlParameterCollection Class , MySql.Data.MySqlClient Namespace Gets the location of a MySqlParameter in the collection. Overload List Gets the location of a MySqlParameter in the collection. Gets the location of the MySqlParameter in the collection with a specific parameter name. See Also MySqlParameterCollection Class , MySql.Data.MySqlClient Namespace Gets the location of a MySqlParameter in the collection. Syntax: Visual Basic NotOverridable Overloads Public Function IndexOf( _ ByVal value As Object _ ) As Integer _ _ Implements IList.IndexOf Syntax: C# public int IndexOf( objectvalue ); Parameters
Return Value The zero-based location of the MySqlParameter in the collection. Implements IList.IndexOf See Also MySqlParameterCollection Class , MySql.Data.MySqlClient Namespace , MySqlParameterCollection.IndexOf Overload List Gets the location of the MySqlParameter in the collection with a specific parameter name. Syntax: Visual Basic NotOverridable Overloads Public Function IndexOf( _ ByVal parameterName As String _ ) As Integer _ _ Implements IDataParameterCollection.IndexOf Syntax: C# public int IndexOf( stringparameterName ); Parameters
Return Value The zero-based location of the MySqlParameter in the collection. Implements IDataParameterCollection.IndexOf See Also MySqlParameterCollection Class , MySql.Data.MySqlClient Namespace , MySqlParameterCollection.IndexOf Overload List Inserts a MySqlParameter into the collection at the specified index. Syntax: Visual Basic NotOverridable Public Sub Insert( _ ByVal index As Integer, _ ByVal value As Object _ ) _ _ Implements IList.Insert Syntax: C# public void Insert( intindex, objectvalue ); Parameters
Implements IList.Insert See Also MySqlParameterCollection Class , MySql.Data.MySqlClient Namespace Removes the specified MySqlParameter from the collection. Syntax: Visual Basic NotOverridable Public Sub Remove( _ ByVal value As Object _ ) _ _ Implements IList.Remove Syntax: C# public void Remove( objectvalue ); Parameters
Implements IList.Remove See Also MySqlParameterCollection Class , MySql.Data.MySqlClient Namespace Removes the specified MySqlParameter from the collection. Overload List Removes the specified MySqlParameter from the collection using a specific index. Removes the specified MySqlParameter from the collection using the parameter name. See Also MySqlParameterCollection Class , MySql.Data.MySqlClient Namespace Removes the specified MySqlParameter from the collection using a specific index. Syntax: Visual Basic NotOverridable Overloads Public Sub RemoveAt( _ ByVal index As Integer _ ) _ _ Implements IList.RemoveAt Syntax: C# public void RemoveAt( intindex ); Parameters
Implements IList.RemoveAt See Also MySqlParameterCollection Class , MySql.Data.MySqlClient Namespace , MySqlParameterCollection.RemoveAt Overload List Removes the specified MySqlParameter from the collection using the parameter name. Syntax: Visual Basic NotOverridable Overloads Public Sub RemoveAt( _ ByVal name As String _ ) _ _ Implements IDataParameterCollection.RemoveAt Syntax: C# public void RemoveAt( stringname ); Parameters
Implements IDataParameterCollection.RemoveAt See Also MySqlParameterCollection Class , MySql.Data.MySqlClient Namespace , MySqlParameterCollection.RemoveAt Overload List Syntax: Visual Basic Public Property Transaction As MySqlTransaction Syntax: C# public MySqlTransaction Transaction {get; set;}See Also Syntax: Visual Basic NotOverridable Public Property UpdatedRowSource As UpdateRowSource _ _ Implements IDbCommand.UpdatedRowSource Syntax: C# public System.Data.UpdateRowSource UpdatedRowSource {get; set;}
Implements IDbCommand.UpdatedRowSource See Also Attempts to cancel the execution of a MySqlCommand. This operation is not supported. Syntax: Visual Basic NotOverridable Public Sub Cancel() _ _ Implements IDbCommand.Cancel Syntax: C# public void Cancel(); Implements IDbCommand.Cancel Remarks Cancelling an executing command is currently not supported on any version of MySQL. Exceptions
See Also Creates a new instance of a MySqlParameter object. Syntax: Visual Basic Public Function CreateParameter() As MySqlParameter Syntax: C# public MySqlParameter CreateParameter(); Return Value A MySqlParameter object. Remarks This method is a strongly-typed version of CreateParameter. See Also Syntax: Visual Basic NotOverridable Public Function ExecuteNonQuery() As Integer _ _ Implements IDbCommand.ExecuteNonQuery Syntax: C# public int ExecuteNonQuery(); Implements IDbCommand.ExecuteNonQuery See Also Overload List See Also MySqlCommand Class , MySql.Data.MySqlClient Namespace Syntax: Visual Basic Overloads Public Function ExecuteReader() As MySqlDataReader Syntax: C# public MySqlDataReader ExecuteReader(); See Also MySqlCommand Class , MySql.Data.MySqlClient Namespace , MySqlCommand.ExecuteReader Overload List Provides a means of reading a forward-only stream of rows from a MySQL database. This class cannot be inherited. For a list of all members of this type, see MySqlDataReader Members . Syntax: Visual Basic NotInheritable Public Class MySqlDataReader_ Inherits MarshalByRefObject_ Implements IEnumerable, IDataReader, IDisposable, IDataRecord Syntax: C# public sealed class MySqlDataReader : MarshalByRefObject, IEnumerable, IDataReader, IDisposable, IDataRecord Thread Safety Public static (Shared in Visual Basic) members of this type are safe for multithreaded operations. Instance members are not guaranteed to be thread-safe. Requirements Namespace: MySql.Data.MySqlClient Assembly: MySql.Data (in MySql.Data.dll) See Also MySqlDataReader Members , MySql.Data.MySqlClient Namespace Public Instance Properties
Public Instance Methods
See Also MySqlDataReader Class , MySql.Data.MySqlClient Namespace Gets a value indicating the depth of nesting for the current row. This method is not supported currently and always returns 0. Syntax: Visual Basic NotOverridable Public ReadOnly Property Depth As Integer _ _ Implements IDataReader.Depth Syntax: C# public int Depth {get;}
Implements IDataReader.Depth See Also Gets the number of columns in the current row. Syntax: Visual Basic NotOverridable Public ReadOnly Property FieldCount As Integer _ _ Implements IDataRecord.FieldCount Syntax: C# public int FieldCount {get;}
Implements IDataRecord.FieldCount See Also Gets a value indicating whether the MySqlDataReader contains one or more rows. Syntax: Visual Basic Public ReadOnly Property HasRows As Boolean Syntax: C# public bool HasRows {get;}See Also Gets a value indicating whether the data reader is closed. Syntax: Visual Basic NotOverridable Public ReadOnly Property IsClosed As Boolean _ _ Implements IDataReader.IsClosed Syntax: C# public bool IsClosed {get;}
Implements IDataReader.IsClosed See Also Overloaded. Gets the value of a column in its native format. In C#, this property is the indexer for the MySqlDataReader class. Overload List Overloaded. Gets the value of a column in its native format. In C#, this property is the indexer for the MySqlDataReader class. Gets the value of a column in its native format. In C#, this property is the indexer for the MySqlDataReader class. See Also MySqlDataReader Class , MySql.Data.MySqlClient Namespace Overloaded. Gets the value of a column in its native format. In C#, this property is the indexer for the MySqlDataReader class. Syntax: Visual Basic NotOverridable Overloads Public Default ReadOnly Property Item( _ ByVal i As Integer _ ) _ _ Implements IDataRecord.Item As Object _ _ Implements IDataRecord.Item Syntax: C# public object this[
inti
] {get;}Implements IDataRecord.Item See Also MySqlDataReader Class , MySql.Data.MySqlClient Namespace , MySqlDataReader.Item Overload List Gets the value of a column in its native format. In C#, this property is the indexer for the MySqlDataReader class. Syntax: Visual Basic NotOverridable Overloads Public Default ReadOnly Property Item( _ ByVal name As String _ ) _ _ Implements IDataRecord.Item As Object _ _ Implements IDataRecord.Item Syntax: C# public object this[
stringname
] {get;}Implements IDataRecord.Item See Also MySqlDataReader Class , MySql.Data.MySqlClient Namespace , MySqlDataReader.Item Overload List Gets the number of rows changed, inserted, or deleted by execution of the SQL statement. Syntax: Visual Basic NotOverridable Public ReadOnly Property RecordsAffected As Integer _ _ Implements IDataReader.RecordsAffected Syntax: C# public int RecordsAffected {get;}
Implements IDataReader.RecordsAffected See Also Closes the MySqlDataReader object. Syntax: Visual Basic NotOverridable Public Sub Close() _ _ Implements IDataReader.Close Syntax: C# public void Close(); Implements IDataReader.Close See Also Gets the value of the specified column as a Boolean. Syntax: Visual Basic NotOverridable Public Function GetBoolean( _ ByVal i As Integer _ ) As Boolean _ _ Implements IDataRecord.GetBoolean Syntax: C# public bool GetBoolean( inti ); Parameters
Return Value Implements IDataRecord.GetBoolean See Also Gets the value of the specified column as a byte. Syntax: Visual Basic NotOverridable Public Function GetByte( _ ByVal i As Integer _ ) As Byte _ _ Implements IDataRecord.GetByte Syntax: C# public byte GetByte( inti ); Parameters
Return Value Implements IDataRecord.GetByte See Also Reads a stream of bytes from the specified column offset into the buffer an array starting at the given buffer offset. Syntax: Visual Basic NotOverridable Public Function GetBytes( _ ByVal i As Integer, _ ByVal dataIndex As Long, _ ByVal buffer As Byte(), _ ByVal bufferIndex As Integer, _ ByVal length As Integer _ ) As Long _ _ Implements IDataRecord.GetBytes Syntax: C# public long GetBytes( inti, longdataIndex, byte[]buffer, intbufferIndex, intlength ); Parameters
Return Value The actual number of bytes read. Implements IDataRecord.GetBytes See Also Gets the value of the specified column as a single character. Syntax: Visual Basic NotOverridable Public Function GetChar( _ ByVal i As Integer _ ) As Char _ _ Implements IDataRecord.GetChar Syntax: C# public char GetChar( inti ); Parameters
Return Value Implements IDataRecord.GetChar See Also Reads a stream of characters from the specified column offset into the buffer as an array starting at the given buffer offset. Syntax: Visual Basic NotOverridable Public Function GetChars( _ ByVal i As Integer, _ ByVal fieldOffset As Long, _ ByVal buffer As Char(), _ ByVal bufferoffset As Integer, _ ByVal length As Integer _ ) As Long _ _ Implements IDataRecord.GetChars Syntax: C# public long GetChars( inti, longfieldOffset, char[]buffer, intbufferoffset, intlength ); Parameters
Return Value Implements IDataRecord.GetChars See Also Gets the name of the source data type. Syntax: Visual Basic NotOverridable Public Function GetDataTypeName( _ ByVal i As Integer _ ) As String _ _ Implements IDataRecord.GetDataTypeName Syntax: C# public string GetDataTypeName( inti ); Parameters
Return Value Implements IDataRecord.GetDataTypeName See Also Syntax: Visual Basic NotOverridable Public Function GetDateTime( _ ByVal index As Integer _ ) As Date _ _ Implements IDataRecord.GetDateTime Syntax: C# public DateTime GetDateTime( intindex ); Implements IDataRecord.GetDateTime See Also Syntax: Visual Basic NotOverridable Public Function GetDecimal( _ ByVal index As Integer _ ) As Decimal _ _ Implements IDataRecord.GetDecimal Syntax: C# public decimal GetDecimal( intindex ); Implements IDataRecord.GetDecimal See Also Syntax: Visual Basic NotOverridable Public Function GetDouble( _ ByVal index As Integer _ ) As Double _ _ Implements IDataRecord.GetDouble Syntax: C# public double GetDouble( intindex ); Implements IDataRecord.GetDouble See Also Gets the Type that is the data type of the object. Syntax: Visual Basic NotOverridable Public Function GetFieldType( _ ByVal i As Integer _ ) As Type _ _ Implements IDataRecord.GetFieldType Syntax: C# public Type GetFieldType( inti ); Parameters
Return Value Implements IDataRecord.GetFieldType See Also Syntax: Visual Basic NotOverridable Public Function GetFloat( _ ByVal index As Integer _ ) As Single _ _ Implements IDataRecord.GetFloat Syntax: C# public float GetFloat( intindex ); Implements IDataRecord.GetFloat See Also Syntax: Visual Basic NotOverridable Public Function GetGuid( _ ByVal index As Integer _ ) As Guid _ _ Implements IDataRecord.GetGuid Syntax: C# public Guid GetGuid( intindex ); Implements IDataRecord.GetGuid See Also Syntax: Visual Basic NotOverridable Public Function GetInt16( _ ByVal index As Integer _ ) As Short _ _ Implements IDataRecord.GetInt16 Syntax: C# public short GetInt16( intindex ); Implements IDataRecord.GetInt16 See Also Syntax: Visual Basic NotOverridable Public Function GetInt32( _ ByVal index As Integer _ ) As Integer _ _ Implements IDataRecord.GetInt32 Syntax: C# public int GetInt32( intindex ); Implements IDataRecord.GetInt32 See Also Syntax: Visual Basic NotOverridable Public Function GetInt64( _ ByVal index As Integer _ ) As Long _ _ Implements IDataRecord.GetInt64 Syntax: C# public long GetInt64( intindex ); Implements IDataRecord.GetInt64 See Also Syntax: Visual Basic Public Function GetMySqlDateTime( _ ByVal index As Integer _ ) As MySqlDateTime Syntax: C# public MySqlDateTime GetMySqlDateTime( intindex ); See Also Gets the name of the specified column. Syntax: Visual Basic NotOverridable Public Function GetName( _ ByVal i As Integer _ ) As String _ _ Implements IDataRecord.GetName Syntax: C# public string GetName( inti ); Parameters
Return Value Implements IDataRecord.GetName See Also Gets the column ordinal, given the name of the column. Syntax: Visual Basic NotOverridable Public Function GetOrdinal( _ ByVal name As String _ ) As Integer _ _ Implements IDataRecord.GetOrdinal Syntax: C# public int GetOrdinal( stringname ); Parameters
Return Value Implements IDataRecord.GetOrdinal See Also Returns a DataTable that describes the column metadata of the MySqlDataReader. Syntax: Visual Basic NotOverridable Public Function GetSchemaTable() As DataTable _ _ Implements IDataReader.GetSchemaTable Syntax: C# public DataTable GetSchemaTable(); Return Value Implements IDataReader.GetSchemaTable See Also Syntax: Visual Basic NotOverridable Public Function GetString( _ ByVal index As Integer _ ) As String _ _ Implements IDataRecord.GetString Syntax: C# public string GetString( intindex ); Implements IDataRecord.GetString See Also Syntax: Visual Basic Public Function GetTimeSpan( _ ByVal index As Integer _ ) As TimeSpan Syntax: C# public TimeSpan GetTimeSpan( intindex ); See Also Syntax: Visual Basic Public Function GetUInt16( _ ByVal index As Integer _ ) As UInt16 Syntax: C# public ushort GetUInt16( intindex ); See Also Syntax: Visual Basic Public Function GetUInt32( _ ByVal index As Integer _ ) As UInt32 Syntax: C# public uint GetUInt32( intindex ); See Also Syntax: Visual Basic Public Function GetUInt64( _ ByVal index As Integer _ ) As UInt64 Syntax: C# public ulong GetUInt64( intindex ); See Also Gets the value of the specified column in its native format. Syntax: Visual Basic NotOverridable Public Function GetValue( _ ByVal i As Integer _ ) As Object _ _ Implements IDataRecord.GetValue Syntax: C# public object GetValue( inti ); Parameters
Return Value Implements IDataRecord.GetValue See Also Gets all attribute columns in the collection for the current row. Syntax: Visual Basic NotOverridable Public Function GetValues( _ ByVal values As Object() _ ) As Integer _ _ Implements IDataRecord.GetValues Syntax: C# public int GetValues( object[]values ); Parameters
Return Value Implements IDataRecord.GetValues See Also Gets a value indicating whether the column contains non-existent or missing values. Syntax: Visual Basic NotOverridable Public Function IsDBNull( _ ByVal i As Integer _ ) As Boolean _ _ Implements IDataRecord.IsDBNull Syntax: C# public bool IsDBNull( inti ); Parameters
Return Value Implements IDataRecord.IsDBNull See Also Advances the data reader to the next result, when reading the results of batch SQL statements. Syntax: Visual Basic NotOverridable Public Function NextResult() As Boolean _ _ Implements IDataReader.NextResult Syntax: C# public bool NextResult(); Return Value Implements IDataReader.NextResult See Also Advances the MySqlDataReader to the next record. Syntax: Visual Basic NotOverridable Public Function Read() As Boolean _ _ Implements IDataReader.Read Syntax: C# public bool Read(); Return Value Implements IDataReader.Read See Also Syntax: Visual Basic Overloads Public Function ExecuteReader( _ ByVal behavior As CommandBehavior _ ) As MySqlDataReader Syntax: C# public MySqlDataReader ExecuteReader( CommandBehaviorbehavior ); See Also MySqlCommand Class , MySql.Data.MySqlClient Namespace , MySqlCommand.ExecuteReader Overload List Syntax: Visual Basic NotOverridable Public Function ExecuteScalar() As Object _ _ Implements IDbCommand.ExecuteScalar Syntax: C# public object ExecuteScalar(); Implements IDbCommand.ExecuteScalar See Also Syntax: Visual Basic NotOverridable Public Sub Prepare() _ _ Implements IDbCommand.Prepare Syntax: C# public void Prepare(); Implements IDbCommand.Prepare See Also For a list of all members of this type, see MySqlCommandBuilder Members . Syntax: Visual Basic NotInheritable Public Class MySqlCommandBuilder_ Inherits Component Syntax: C# public sealed class MySqlCommandBuilder : Component Thread Safety Public static (Sharedin Visual Basic) members of this type are safe for multithreaded operations. Instance members are notguaranteed to be thread-safe. Requirements Namespace: MySql.Data.MySqlClient Assembly: MySql.Data (in MySql.Data.dll) See Also MySqlCommandBuilder Members , MySql.Data.MySqlClient Namespace
Public Static (Shared) Methods
Public Instance Constructors
Public Instance Properties
Public Instance Methods
Public Instance Events
See Also MySqlCommandBuilder Class , MySql.Data.MySqlClient Namespace Retrieves parameter information from the stored procedure specified in the MySqlCommand and populates the Parameters collection of the specified MySqlCommand object. This method is not currently supported since stored procedures are not available in MySql. Overload List Retrieves parameter information from the stored procedure specified in the MySqlCommand and populates the Parameters collection of the specified MySqlCommand object. This method is not currently supported since stored procedures are not available in MySql. See Also MySqlCommandBuilder Class , MySql.Data.MySqlClient Namespace Retrieves parameter information from the stored procedure specified in the MySqlCommand and populates the Parameters collection of the specified MySqlCommand object. This method is not currently supported since stored procedures are not available in MySql. Syntax: Visual Basic Overloads Public Shared Sub DeriveParameters( _ ByVal command As MySqlCommand _ ) Syntax: C# public static void DeriveParameters( MySqlCommandcommand ); Parameters
Exceptions
See Also MySqlCommandBuilder Class , MySql.Data.MySqlClient Namespace , MySqlCommandBuilder.DeriveParameters Overload List Syntax: Visual Basic Overloads Public Shared Sub DeriveParameters( _ ByVal command As MySqlCommand, _ ByVal useProc As Boolean _ ) Syntax: C# public static void DeriveParameters( MySqlCommandcommand, booluseProc ); See Also MySqlCommandBuilder Class , MySql.Data.MySqlClient Namespace , MySqlCommandBuilder.DeriveParameters Overload List Initializes a new instance of the MySqlCommandBuilder class. Overload List Initializes a new instance of the MySqlCommandBuilder class. See Also MySqlCommandBuilder Class , MySql.Data.MySqlClient Namespace Initializes a new instance of the MySqlCommandBuilder class. Syntax: Visual Basic Overloads Public Sub New() Syntax: C# public MySqlCommandBuilder(); See Also MySqlCommandBuilder Class , MySql.Data.MySqlClient Namespace , MySqlCommandBuilder Constructor Overload List Syntax: Visual Basic Overloads Public Sub New( _ ByVal adapter As MySqlDataAdapter _ ) Syntax: C# public MySqlCommandBuilder( MySqlDataAdapteradapter ); See Also MySqlCommandBuilder Class , MySql.Data.MySqlClient Namespace , MySqlCommandBuilder Constructor Overload List For a list of all members of this type, see MySqlDataAdapter Members . Syntax: Visual Basic NotInheritable Public Class MySqlDataAdapter_ Inherits DbDataAdapter Syntax: C# public sealed class MySqlDataAdapter : DbDataAdapter Thread Safety Public static (Sharedin Visual Basic) members of this type are safe for multithreaded operations. Instance members are notguaranteed to be thread-safe. Requirements Namespace: MySql.Data.MySqlClient Assembly: MySql.Data (in MySql.Data.dll) See Also MySqlDataAdapter Members , MySql.Data.MySqlClient Namespace Public Instance Constructors
Public Instance Properties
Public Instance Methods
Public Instance Events
Protected Internal Instance Properties
See Also MySqlDataAdapter Class , MySql.Data.MySqlClient Namespace Initializes a new instance of the MySqlDataAdapter class. Overload List Initializes a new instance of the MySqlDataAdapter class. See Also MySqlDataAdapter Class , MySql.Data.MySqlClient Namespace Initializes a new instance of the MySqlDataAdapter class. Syntax: Visual Basic Overloads Public Sub New() Syntax: C# public MySqlDataAdapter(); See Also MySqlDataAdapter Class , MySql.Data.MySqlClient Namespace , MySqlDataAdapter Constructor Overload List Syntax: Visual Basic Overloads Public Sub New( _ ByVal selectCommand As MySqlCommand _ ) Syntax: C# public MySqlDataAdapter( MySqlCommandselectCommand ); See Also MySqlDataAdapter Class , MySql.Data.MySqlClient Namespace , MySqlDataAdapter Constructor Overload List Syntax: Visual Basic Overloads Public Sub New( _ ByVal selectCommandText As String, _ ByVal connection As MySqlConnection _ ) Syntax: C# public MySqlDataAdapter( stringselectCommandText, MySqlConnectionconnection ); See Also MySqlDataAdapter Class , MySql.Data.MySqlClient Namespace , MySqlDataAdapter Constructor Overload List Syntax: Visual Basic Overloads Public Sub New( _ ByVal selectCommandText As String, _ ByVal selectConnString As String _ ) Syntax: C# public MySqlDataAdapter( stringselectCommandText, stringselectConnString ); See Also MySqlDataAdapter Class , MySql.Data.MySqlClient Namespace , MySqlDataAdapter Constructor Overload List Syntax: Visual Basic Overloads Public Property DeleteCommand As MySqlCommand Syntax: C# new public MySqlCommand DeleteCommand {get; set;}See Also Syntax: Visual Basic Overloads Public Property InsertCommand As MySqlCommand Syntax: C# new public MySqlCommand InsertCommand {get; set;}See Also Syntax: Visual Basic Overloads Public Property SelectCommand As MySqlCommand Syntax: C# new public MySqlCommand SelectCommand {get; set;}See Also Syntax: Visual Basic Overloads Public Property UpdateCommand As MySqlCommand Syntax: C# new public MySqlCommand UpdateCommand {get; set;}See Also Occurs during Update after a command is executed against the data source. The attempt to update is made, so the event fires. Syntax: Visual Basic Public Event RowUpdated As MySqlRowUpdatedEventHandler Syntax: C# public event MySqlRowUpdatedEventHandler RowUpdated; Event Data The event handler receives an argument of type MySqlRowUpdatedEventArgs containing data related to this event. The following MySqlRowUpdatedEventArgsproperties provide information specific to this event.
See Also MySqlDataAdapter Class , MySql.Data.MySqlClient Namespace Represents the method that will handle the RowUpdatedevent of a MySqlDataAdapter . Syntax: Visual Basic Public Delegate Sub MySqlRowUpdatedEventHandler( _ ByVal sender As Object, _ ByVal e As MySqlRowUpdatedEventArgs _ ) Syntax: C# public delegate void MySqlRowUpdatedEventHandler( objectsender, MySqlRowUpdatedEventArgse ); Requirements Namespace: MySql.Data.MySqlClient Assembly: MySql.Data (in MySql.Data.dll) See Also MySql.Data.MySqlClient Namespace Provides data for the RowUpdated event. This class cannot be inherited. For a list of all members of this type, see MySqlRowUpdatedEventArgs Members . Syntax: Visual Basic NotInheritable Public Class MySqlRowUpdatedEventArgs_ Inherits RowUpdatedEventArgs Syntax: C# public sealed class MySqlRowUpdatedEventArgs : RowUpdatedEventArgs Thread Safety Public static (Sharedin Visual Basic) members of this type are safe for multithreaded operations. Instance members are notguaranteed to be thread-safe. Requirements Namespace: MySql.Data.MySqlClient Assembly: MySql.Data (in MySql.Data.dll) See Also MySqlRowUpdatedEventArgs Members , MySql.Data.MySqlClient Namespace MySqlRowUpdatedEventArgs overview Public Instance Constructors
Public Instance Properties
Public Instance Methods
See Also MySqlRowUpdatedEventArgs Class , MySql.Data.MySqlClient Namespace Initializes a new instance of the MySqlRowUpdatedEventArgs class. Syntax: Visual Basic Public Sub New( _ ByVal row As DataRow, _ ByVal command As IDbCommand, _ ByVal statementType As StatementType, _ ByVal tableMapping As DataTableMapping _ ) Syntax: C# public MySqlRowUpdatedEventArgs( DataRowrow, IDbCommandcommand, StatementTypestatementType, DataTableMappingtableMapping ); Parameters
See Also MySqlRowUpdatedEventArgs Class , MySql.Data.MySqlClient Namespace Gets or sets the MySqlCommand executed when Update is called. Syntax: Visual Basic Overloads Public ReadOnly Property Command As MySqlCommand Syntax: C# new public MySqlCommand Command {get;}See Also MySqlRowUpdatedEventArgs Class , MySql.Data.MySqlClient Namespace Occurs during Update before a command is executed against the data source. The attempt to update is made, so the event fires. Syntax: Visual Basic Public Event RowUpdating As MySqlRowUpdatingEventHandler Syntax: C# public event MySqlRowUpdatingEventHandler RowUpdating; Event Data The event handler receives an argument of type MySqlRowUpdatingEventArgs containing data related to this event. The following MySqlRowUpdatingEventArgsproperties provide information specific to this event.
See Also MySqlDataAdapter Class , MySql.Data.MySqlClient Namespace Represents the method that will handle the RowUpdatingevent of a MySqlDataAdapter . Syntax: Visual Basic Public Delegate Sub MySqlRowUpdatingEventHandler( _ ByVal sender As Object, _ ByVal e As MySqlRowUpdatingEventArgs _ ) Syntax: C# public delegate void MySqlRowUpdatingEventHandler( objectsender, MySqlRowUpdatingEventArgse ); Requirements Namespace: MySql.Data.MySqlClient Assembly: MySql.Data (in MySql.Data.dll) See Also MySql.Data.MySqlClient Namespace Provides data for the RowUpdating event. This class cannot be inherited. For a list of all members of this type, see MySqlRowUpdatingEventArgs Members . Syntax: Visual Basic NotInheritable Public Class MySqlRowUpdatingEventArgs_ Inherits RowUpdatingEventArgs Syntax: C# public sealed class MySqlRowUpdatingEventArgs : RowUpdatingEventArgs Thread Safety Public static (Sharedin Visual Basic) members of this type are safe for multithreaded operations. Instance members are notguaranteed to be thread-safe. Requirements Namespace: MySql.Data.MySqlClient Assembly: MySql.Data (in MySql.Data.dll) See Also MySqlRowUpdatingEventArgs Members , MySql.Data.MySqlClient Namespace MySqlRowUpdatingEventArgs overview Public Instance Constructors
Public Instance Properties
Public Instance Methods
See Also MySqlRowUpdatingEventArgs Class , MySql.Data.MySqlClient Namespace Initializes a new instance of the MySqlRowUpdatingEventArgs class. Syntax: Visual Basic Public Sub New( _ ByVal row As DataRow, _ ByVal command As IDbCommand, _ ByVal statementType As StatementType, _ ByVal tableMapping As DataTableMapping _ ) Syntax: C# public MySqlRowUpdatingEventArgs( DataRowrow, IDbCommandcommand, StatementTypestatementType, DataTableMappingtableMapping ); Parameters
See Also MySqlRowUpdatingEventArgs Class , MySql.Data.MySqlClient Namespace Gets or sets the MySqlCommand to execute when performing the Update. Syntax: Visual Basic Overloads Public Property Command As MySqlCommand Syntax: C# new public MySqlCommand Command {get; set;}See Also MySqlRowUpdatingEventArgs Class , MySql.Data.MySqlClient Namespace Syntax: Visual Basic Overloads Public Sub New( _ ByVal adapter As MySqlDataAdapter, _ ByVal lastOneWins As Boolean _ ) Syntax: C# public MySqlCommandBuilder( MySqlDataAdapteradapter, boollastOneWins ); See Also MySqlCommandBuilder Class , MySql.Data.MySqlClient Namespace , MySqlCommandBuilder Constructor Overload List Syntax: Visual Basic Overloads Public Sub New( _ ByVal lastOneWins As Boolean _ ) Syntax: C# public MySqlCommandBuilder( boollastOneWins ); See Also MySqlCommandBuilder Class , MySql.Data.MySqlClient Namespace , MySqlCommandBuilder Constructor Overload List Syntax: Visual Basic Public Property DataAdapter As MySqlDataAdapter Syntax: C# public MySqlDataAdapter DataAdapter {get; set;}See Also MySqlCommandBuilder Class , MySql.Data.MySqlClient Namespace Syntax: Visual Basic Public Property QuotePrefix As String Syntax: C# public string QuotePrefix {get; set;}See Also MySqlCommandBuilder Class , MySql.Data.MySqlClient Namespace Syntax: Visual Basic Public Property QuoteSuffix As String Syntax: C# public string QuoteSuffix {get; set;}See Also MySqlCommandBuilder Class , MySql.Data.MySqlClient Namespace Syntax: Visual Basic Public Function GetDeleteCommand() As MySqlCommand Syntax: C# public MySqlCommand GetDeleteCommand(); See Also MySqlCommandBuilder Class , MySql.Data.MySqlClient Namespace Syntax: Visual Basic Public Function GetInsertCommand() As MySqlCommand Syntax: C# public MySqlCommand GetInsertCommand(); See Also MySqlCommandBuilder Class , MySql.Data.MySqlClient Namespace Syntax: Visual Basic Public Function GetUpdateCommand() As MySqlCommand Syntax: C# public MySqlCommand GetUpdateCommand(); See Also MySqlCommandBuilder Class , MySql.Data.MySqlClient Namespace Syntax: Visual Basic Public Sub RefreshSchema() Syntax: C# public void RefreshSchema(); See Also MySqlCommandBuilder Class , MySql.Data.MySqlClient Namespace The exception that is thrown when MySQL returns an error. This class cannot be inherited. For a list of all members of this type, see MySqlException Members . Syntax: Visual Basic NotInheritable Public Class MySqlException_ Inherits SystemException Syntax: C# public sealed class MySqlException : SystemException Thread Safety Public static (Sharedin Visual Basic) members of this type are safe for multithreaded operations. Instance members are notguaranteed to be thread-safe. Requirements Namespace: MySql.Data.MySqlClient Assembly: MySql.Data (in MySql.Data.dll) See Also MySqlException Members , MySql.Data.MySqlClient Namespace Public Instance Properties
Public Instance Methods
See Also MySqlException Class , MySql.Data.MySqlClient Namespace Gets a number that identifies the type of error. Syntax: Visual Basic Public ReadOnly Property Number As Integer Syntax: C# public int Number {get;}See Also Helper class that makes it easier to work with the provider. For a list of all members of this type, see MySqlHelper Members . Syntax: Visual Basic NotInheritable Public Class MySqlHelper Syntax: C# public sealed class MySqlHelper Thread Safety Public static (Shared in Visual Basic) members of this type are safe for multithreaded operations. Instance members are not guaranteed to be thread-safe. Requirements Namespace: MySql.Data.MySqlClient Assembly: MySql.Data (in MySql.Data.dll) See Also MySqlHelper Members , MySql.Data.MySqlClient Namespace Public Static (Shared) Methods
Public Instance Methods
See Also MySqlHelper Class , MySql.Data.MySqlClient Namespace Executes a single SQL command and returns the first row of the resultset. A new MySqlConnection object is created, opened, and closed during this method. Syntax: Visual Basic Public Shared Function ExecuteDataRow( _ ByVal connectionString As String, _ ByVal commandText As String, _ ParamArray parms As MySqlParameter() _ ) As DataRow Syntax: C# public static DataRow ExecuteDataRow( stringconnectionString, stringcommandText, params MySqlParameter[]parms ); Parameters
Return Value DataRow containing the first row of the resultset See Also Executes a single SQL command and returns the resultset in a DataSet. The state of the MySqlConnection object remains unchanged after execution of this method. Overload List Executes a single SQL command and returns the resultset in a DataSet. The state of the MySqlConnection object remains unchanged after execution of this method. Executes a single SQL command and returns the resultset in a DataSet. The state of the MySqlConnection object remains unchanged after execution of this method. Executes a single SQL command and returns the resultset in a DataSet. A new MySqlConnection object is created, opened, and closed during this method. Executes a single SQL command and returns the resultset in a DataSet. A new MySqlConnection object is created, opened, and closed during this method. See Also MySqlHelper Class , MySql.Data.MySqlClient Namespace Executes a single SQL command and returns the resultset in a DataSet. The state of the MySqlConnection object remains unchanged after execution of this method. Syntax: Visual Basic Overloads Public Shared Function ExecuteDataset( _ ByVal connection As MySqlConnection, _ ByVal commandText As String _ ) As DataSet Syntax: C# public static DataSet ExecuteDataset( MySqlConnectionconnection, stringcommandText ); Parameters
Return Value DataSetcontaining the resultset See Also MySqlHelper Class , MySql.Data.MySqlClient Namespace , MySqlHelper.ExecuteDataset Overload List Executes a single SQL command and returns the resultset in a DataSet. The state of the MySqlConnection object remains unchanged after execution of this method. Syntax: Visual Basic Overloads Public Shared Function ExecuteDataset( _ ByVal connection As MySqlConnection, _ ByVal commandText As String, _ ParamArray commandParameters As MySqlParameter() _ ) As DataSet Syntax: C# public static DataSet ExecuteDataset( MySqlConnectionconnection, stringcommandText, params MySqlParameter[]commandParameters ); Parameters
Return Value DataSetcontaining the resultset See Also MySqlHelper Class , MySql.Data.MySqlClient Namespace , MySqlHelper.ExecuteDataset Overload List Executes a single SQL command and returns the resultset in a DataSet. A new MySqlConnection object is created, opened, and closed during this method. Syntax: Visual Basic Overloads Public Shared Function ExecuteDataset( _ ByVal connectionString As String, _ ByVal commandText As String _ ) As DataSet Syntax: C# public static DataSet ExecuteDataset( stringconnectionString, stringcommandText ); Parameters
Return Value DataSetcontaining the resultset See Also MySqlHelper Class , MySql.Data.MySqlClient Namespace , MySqlHelper.ExecuteDataset Overload List Executes a single SQL command and returns the resultset in a DataSet. A new MySqlConnection object is created, opened, and closed during this method. Syntax: Visual Basic Overloads Public Shared Function ExecuteDataset( _ ByVal connectionString As String, _ ByVal commandText As String, _ ParamArray commandParameters As MySqlParameter() _ ) As DataSet Syntax: C# public static DataSet ExecuteDataset( stringconnectionString, stringcommandText, params MySqlParameter[]commandParameters ); Parameters
Return Value DataSetcontaining the resultset See Also MySqlHelper Class , MySql.Data.MySqlClient Namespace , MySqlHelper.ExecuteDataset Overload List Executes a single command against a MySQL database. The MySqlConnection is assumed to be open when the method is called and remains open after the method completes. Overload List Executes a single command against a MySQL database. The MySqlConnection is assumed to be open when the method is called and remains open after the method completes. Executes a single command against a MySQL database. A new MySqlConnection is created using the ConnectionString given. See Also MySqlHelper Class , MySql.Data.MySqlClient Namespace Executes a single command against a MySQL database. The MySqlConnection is assumed to be open when the method is called and remains open after the method completes. Syntax: Visual Basic Overloads Public Shared Function ExecuteNonQuery( _ ByVal connection As MySqlConnection, _ ByVal commandText As String, _ ParamArray commandParameters As MySqlParameter() _ ) As Integer Syntax: C# public static int ExecuteNonQuery( MySqlConnectionconnection, stringcommandText, params MySqlParameter[]commandParameters ); Parameters
Return Value See Also MySqlHelper Class , MySql.Data.MySqlClient Namespace , MySqlHelper.ExecuteNonQuery Overload List Executes a single command against a MySQL database. A new MySqlConnection is created using the ConnectionString given. Syntax: Visual Basic Overloads Public Shared Function ExecuteNonQuery( _ ByVal connectionString As String, _ ByVal commandText As String, _ ParamArray parms As MySqlParameter() _ ) As Integer Syntax: C# public static int ExecuteNonQuery( stringconnectionString, stringcommandText, params MySqlParameter[]parms ); Parameters
Return Value See Also MySqlHelper Class , MySql.Data.MySqlClient Namespace , MySqlHelper.ExecuteNonQuery Overload List Executes a single command against a MySQL database. Overload List Executes a single command against a MySQL database. Executes a single command against a MySQL database. See Also MySqlHelper Class , MySql.Data.MySqlClient Namespace Executes a single command against a MySQL database. Syntax: Visual Basic Overloads Public Shared Function ExecuteReader( _ ByVal connectionString As String, _ ByVal commandText As String _ ) As MySqlDataReader Syntax: C# public static MySqlDataReader ExecuteReader( stringconnectionString, stringcommandText ); Parameters
Return Value MySqlDataReader object ready to read the results of the command See Also MySqlHelper Class , MySql.Data.MySqlClient Namespace , MySqlHelper.ExecuteReader Overload List Executes a single command against a MySQL database. Syntax: Visual Basic Overloads Public Shared Function ExecuteReader( _ ByVal connectionString As String, _ ByVal commandText As String, _ ParamArray commandParameters As MySqlParameter() _ ) As MySqlDataReader Syntax: C# public static MySqlDataReader ExecuteReader( stringconnectionString, stringcommandText, params MySqlParameter[]commandParameters ); Parameters
Return Value MySqlDataReader object ready to read the results of the command See Also MySqlHelper Class , MySql.Data.MySqlClient Namespace , MySqlHelper.ExecuteReader Overload List Execute a single command against a MySQL database. Overload List Execute a single command against a MySQL database. Execute a single command against a MySQL database. Execute a single command against a MySQL database. Execute a single command against a MySQL database. See Also MySqlHelper Class , MySql.Data.MySqlClient Namespace Execute a single command against a MySQL database. Syntax: Visual Basic Overloads Public Shared Function ExecuteScalar( _ ByVal connection As MySqlConnection, _ ByVal commandText As String _ ) As Object Syntax: C# public static object ExecuteScalar( MySqlConnectionconnection, stringcommandText ); Parameters
Return Value The first column of the first row in the result set, or a null reference if the result set is empty. See Also MySqlHelper Class , MySql.Data.MySqlClient Namespace , MySqlHelper.ExecuteScalar Overload List Execute a single command against a MySQL database. Syntax: Visual Basic Overloads Public Shared Function ExecuteScalar( _ ByVal connection As MySqlConnection, _ ByVal commandText As String, _ ParamArray commandParameters As MySqlParameter() _ ) As Object Syntax: C# public static object ExecuteScalar( MySqlConnectionconnection, stringcommandText, params MySqlParameter[]commandParameters ); Parameters
Return Value The first column of the first row in the result set, or a null reference if the result set is empty. See Also MySqlHelper Class , MySql.Data.MySqlClient Namespace , MySqlHelper.ExecuteScalar Overload List Execute a single command against a MySQL database. Syntax: Visual Basic Overloads Public Shared Function ExecuteScalar( _ ByVal connectionString As String, _ ByVal commandText As String _ ) As Object Syntax: C# public static object ExecuteScalar( stringconnectionString, stringcommandText ); Parameters
Return Value The first column of the first row in the result set, or a null reference if the result set is empty. See Also MySqlHelper Class , MySql.Data.MySqlClient Namespace , MySqlHelper.ExecuteScalar Overload List Execute a single command against a MySQL database. Syntax: Visual Basic Overloads Public Shared Function ExecuteScalar( _ ByVal connectionString As String, _ ByVal commandText As String, _ ParamArray commandParameters As MySqlParameter() _ ) As Object Syntax: C# public static object ExecuteScalar( stringconnectionString, stringcommandText, params MySqlParameter[]commandParameters ); Parameters
Return Value The first column of the first row in the result set, or a null reference if the result set is empty. See Also MySqlHelper Class , MySql.Data.MySqlClient Namespace , MySqlHelper.ExecuteScalar Overload List Updates the given table with data from the given DataSet Syntax: Visual Basic Public Shared Sub UpdateDataSet( _ ByVal connectionString As String, _ ByVal commandText As String, _ ByVal ds As DataSet, _ ByVal tablename As String _ ) Syntax: C# public static void UpdateDataSet( stringconnectionString, stringcommandText, DataSetds, stringtablename ); Parameters
See Also Syntax: Visual Basic Public Enum MySqlErrorCode Syntax: C# public enum MySqlErrorCode Members
Requirements Namespace: MySql.Data.MySqlClient Assembly: MySql.Data (in MySql.Data.dll) See Also Classes
Summary description for MySqlConversionException. For a list of all members of this type, see MySqlConversionException Members . Syntax: Visual Basic Public Class MySqlConversionException_ Inherits ApplicationException Syntax: C# public class MySqlConversionException : ApplicationException Thread Safety Public static (Sharedin Visual Basic) members of this type are safe for multithreaded operations. Instance members are notguaranteed to be thread-safe. Requirements Namespace: MySql.Data.Types Assembly: MySql.Data (in MySql.Data.dll) See Also MySqlConversionException Members , MySql.Data.Types Namespace MySqlConversionException overview Public Instance Constructors Public Instance Properties
Public Instance Methods
Protected Instance Properties
Protected Instance Methods
See Also MySqlConversionException Class , MySql.Data.Types Namespace Syntax: Visual Basic Public Sub New( _ ByVal msg As String _ ) Syntax: C# public MySqlConversionException( stringmsg ); See Also Summary description for MySqlDateTime. For a list of all members of this type, see MySqlDateTime Members . Syntax: Visual Basic Public Class MySqlDateTime_ Inherits MySqlValue_ Implements IConvertible, IComparable Syntax: C# public class MySqlDateTime : MySqlValue, IConvertible, IComparable Thread Safety Public static (Shared in Visual Basic) members of this type are safe for multithreaded operations. Instance members are not guaranteed to be thread-safe. Requirements Namespace: MySql.Data.Types Assembly: MySql.Data (in MySql.Data.dll) See Also MySqlDateTime Members , MySql.Data.Types Namespace
Public Static (Shared) Type Conversions Public Instance Properties
Public Instance Methods
Protected Instance Fields
Protected Instance Methods
See Also MySqlDateTime Class , MySql.Data.Types Namespace Syntax: Visual Basic MySqlDateTime.op_Explicit(val) Syntax: C# public static explicit operator DateTime( MySqlDateTimeval ); Parameters
Return Value See Also Returns the day portion of this datetime Syntax: Visual Basic Public Property Day As Integer Syntax: C# public int Day {get; set;}See Also Returns the hour portion of this datetime Syntax: Visual Basic Public Property Hour As Integer Syntax: C# public int Hour {get; set;}See Also Syntax: Visual Basic Public Property IsNull As Boolean Syntax: C# public bool IsNull {get; set;}See Also MySqlValue Class , MySql.Data.Types Namespace For a list of all members of this type, see MySqlValue Members . Syntax: Visual Basic MustInherit Public Class MySqlValue Syntax: C# public abstract class MySqlValue Thread Safety Public static (Shared in Visual Basic) members of this type are safe for multithreaded operations. Instance members are not guaranteed to be thread-safe. Requirements Namespace: MySql.Data.Types Assembly: MySql.Data (in MySql.Data.dll) See Also MySqlValue Members , MySql.Data.Types Namespace
Protected Static (Shared) Fields Public Instance Constructors
Public Instance Properties
Public Instance Methods
Protected Instance Fields
Protected Instance Methods
See Also MySqlValue Class , MySql.Data.Types Namespace Syntax: Visual Basic Protected Shared numberFormat As NumberFormatInfo Syntax: C# protected static NumberFormatInfo numberFormat; See Also Initializes a new instance of the MySqlValue class. Syntax: Visual Basic Public Sub New() Syntax: C# public MySqlValue(); See Also Returns the value of this field as an object Syntax: Visual Basic Public ReadOnly Property ValueAsObject As Object Syntax: C# public object ValueAsObject {get;}See Also Returns a string representation of this value Syntax: Visual Basic Overrides Public Function ToString() As String Syntax: C# public override string ToString(); See Also The system type represented by this value Syntax: Visual Basic Protected classType As Type Syntax: C# protected Type classType; See Also The generic dbtype of this value Syntax: Visual Basic Protected dbType As DbType Syntax: C# protected DbType dbType; See Also The specific MySQL db type Syntax: Visual Basic Protected mySqlDbType As MySqlDbType Syntax: C# protected MySqlDbType mySqlDbType; See Also The MySQL specific typename of this value Syntax: Visual Basic Protected mySqlTypeName As String Syntax: C# protected string mySqlTypeName; See Also Syntax: Visual Basic Protected objectValue As Object Syntax: C# protected object objectValue; See Also Indicates if this object contains a value that can be represented as a DateTime Syntax: Visual Basic Public ReadOnly Property IsValidDateTime As Boolean Syntax: C# public bool IsValidDateTime {get;}See Also Returns the minute portion of this datetime Syntax: Visual Basic Public Property Minute As Integer Syntax: C# public int Minute {get; set;}See Also Returns the month portion of this datetime Syntax: Visual Basic Public Property Month As Integer Syntax: C# public int Month {get; set;}See Also Returns the second portion of this datetime Syntax: Visual Basic Public Property Second As Integer Syntax: C# public int Second {get; set;}See Also Returns the year portion of this datetime Syntax: Visual Basic Public Property Year As Integer Syntax: C# public int Year {get; set;}See Also Returns this value as a DateTime Syntax: Visual Basic Public Function GetDateTime() As Date Syntax: C# public DateTime GetDateTime(); See Also Returns a MySQL specific string representation of this value Syntax: Visual Basic Overrides Public Function ToString() As String Syntax: C# public override string ToString(); See Also
In this section we will cover some of the more common use cases for Connector/NET, including BLOB handling, date handling, and using Connector/NET with common tools such as Crystal Reports.
All interaction between a .NET application and the MySQL
server is routed through a
Even when using the
In this section, we will describe how to connect to MySQL
using the
The The following is a sample connection string: Server=127.0.0.1;Uid=root;Pwd=12345;Database=test;
In this example, the The following options are typically used (a full list of options is available in the API documentation for Section 23.2.3.3.15, “ConnectionString”):
Once you have created a connection string it can be used to open a connection to the MySQL server.
The following code is used to create a
Visual Basic Example Dim conn As New MySql.Data.MySqlClient.MySqlConnection
Dim myConnectionString as String
myConnectionString = "server=127.0.0.1;" _
& "uid=root;" _
& "pwd=12345;" _
& "database=test;"
Try
conn.ConnectionString = myConnectionString
conn.Open()
Catch ex As MySql.Data.MySqlClient.MySqlException
MessageBox.Show(ex.Message)
End Try
C# Example MySql.Data.MySqlClient.MySqlConnection conn;
string myConnectionString;
myConnectionString = "server=127.0.0.1;uid=root;" +
"pwd=12345;database=test;";
try
{
conn = new MySql.Data.MySqlClient.MySqlConnection();
conn.ConnectionString = myConnectionString;
conn.Open();
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
MessageBox.Show(ex.Message);
}
You can also pass the connection string to the constructor of
the Visual Basic Example Dim myConnectionString as String
myConnectionString = "server=127.0.0.1;" _
& "uid=root;" _
& "pwd=12345;" _
& "database=test;"
Try
Dim conn As New MySql.Data.MySqlClient.MySqlConnection(myConnectionString)
conn.Open()
Catch ex As MySql.Data.MySqlClient.MySqlException
MessageBox.Show(ex.Message)
End Try
C# Example MySql.Data.MySqlClient.MySqlConnection conn;
string myConnectionString;
myConnectionString = "server=127.0.0.1;uid=root;" +
"pwd=12345;database=test;";
try
{
conn = new MySql.Data.MySqlClient.MySqlConnection(myConnectionString);
conn.Open();
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
MessageBox.Show(ex.Message);
}
Once the connection is open it can be used by the other Connector/NET classes to communicate with the MySQL server.
Because connecting to an external server is unpredictable, it
is important to add error handling to your .NET application.
When there is an error connecting, the
When handling errors, you can your application's response based on the error number. The two most common error numbers when connecting are as follows:
The following code shows how to adapt the application's response based on the actual error: Visual Basic Example Dim myConnectionString as String
myConnectionString = "server=127.0.0.1;" _
& "uid=root;" _
& "pwd=12345;" _
& "database=test;"
Try
Dim conn As New MySql.Data.MySqlClient.MySqlConnection(myConnectionString)
conn.Open()
Catch ex As MySql.Data.MySqlClient.MySqlException
Select Case ex.Number
Case 0
MessageBox.Show("Cannot connect to server. Contact administrator")
Case 1045
MessageBox.Show("Invalid username/password, please try again")
End Select
End Try
C# Example MySql.Data.MySqlClient.MySqlConnection conn;
string myConnectionString;
myConnectionString = "server=127.0.0.1;uid=root;" +
"pwd=12345;database=test;";
try
{
conn = new MySql.Data.MySqlClient.MySqlConnection(myConnectionString);
conn.Open();
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
switch (ex.Number)
{
case 0:
MessageBox.Show("Cannot connect to server. Contact administrator");
case 1045:
MessageBox.Show("Invalid username/password, please try again");
}
}
Important: Note that if you
are using multilanguage databases you must specify the
character set in the connection string. If you do not specify
the character set, the connection defaults to the
MySqlConnection myConnection = new MySqlConnection("server=127.0.0.1;uid=root;" +
"pwd=12345;database=test;Charset=latin1;");
As of MySQL 4.1, it is possible to use prepared statements with Connector/NET. Use of prepared statements can provide significant performance improvements on queries that are executed more than once. Prepared execution is faster than direct execution for statements executed more than once, primarily because the query is parsed only once. In the case of direct execution, the query is parsed every time it is executed. Prepared execution also can provide a reduction of network traffic because for each execution of the prepared statement, it is necessary only to send the data for the parameters. Another advantage of prepared statements is that it uses a binary protocol that makes data transfer between client and server more efficient.
To prepare a statement, create a command object and set the
After entering your statement, call the
After you enter your query and enter parameters, execute the
statement using the
For subsequent executions, you need only modify the values of
the parameters and call the execute method again, there is no
need to set the Visual Basic Example Dim conn As New MySqlConnection
Dim cmd As New MySqlCommand
conn.ConnectionString = strConnection
Try
conn.Open()
cmd.Connection = conn
cmd.CommandText = "INSERT INTO myTable VALUES(NULL, ?number, ?text)"
cmd.Prepare()
cmd.Parameters.Add("?number", 1)
cmd.Parameters.Add("?text", "One")
For i = 1 To 1000
cmd.Parameters["?number"].Value = i
cmd.Parameters["?text"].Value = "A string value"
cmd.ExecuteNonQuery()
Next
Catch ex As MySqlException
MessageBox.Show("Error " & ex.Number & " has occurred: " & ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
C# Example MySql.Data.MySqlClient.MySqlConnection conn;
MySql.Data.MySqlClient.MySqlCommand cmd;
conn = new MySql.Data.MySqlClient.MySqlConnection();
cmd = new MySql.Data.MySqlClient.MySqlCommand();
conn.ConnectionString = strConnection;
try
{
conn.Open();
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO myTable VALUES(NULL, ?number, ?text)";
cmd.Prepare();
cmd.Parameters.Add("?number", 1);
cmd.Parameters.Add("?text", "One");
for (int i=1; i <= 1000; i++)
{
cmd.Parameters["?number"].Value = i;
cmd.Parameters["?text"].Value = "A string value";
cmd.ExecuteNonQuery();
}
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
MessageBox.Show("Error " + ex.Number + " has occurred: " + ex.Message,
"Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
With the release of MySQL version 5 the MySQL server now supports stored procedures with the SQL 2003 stored procedure syntax. A stored procedure is a set of SQL statements that can be stored in the server. Once this has been done, clients don't need to keep reissuing the individual statements but can refer to the stored procedure instead. Stored procedures can be particularly useful in situations such as the following:
Connector/NET supports the calling of stored procedures
through the Note
When you call a stored procedure, the command object makes
an additional This section will not provide in-depth information on creating Stored Procedures. For such information, please refer to http://dev.mysql.com/doc/mysql/en/stored-procedures.html.
A sample application demonstrating how to use stored
procedures with Connector/NET can be found in the
Stored procedures in MySQL can be created using a variety of
tools. First, stored procedures can be created using the
mysql command-line client. Second, stored
procedures can be created using the Visual Basic Example Dim conn As New MySqlConnection
Dim cmd As New MySqlCommand
conn.ConnectionString = "server=127.0.0.1;" _
& "uid=root;" _
& "pwd=12345;" _
& "database=test"
Try
conn.Open()
cmd.Connection = conn
cmd.CommandText = "CREATE PROCEDURE add_emp(" _
& "IN fname VARCHAR(20), IN lname VARCHAR(20), IN bday DATETIME, OUT empno INT) " _
& "BEGIN INSERT INTO emp(first_name, last_name, birthdate) " _
& "VALUES(fname, lname, DATE(bday)); SET empno = LAST_INSERT_ID(); END"
cmd.ExecuteNonQuery()
Catch ex As MySqlException
MessageBox.Show("Error " & ex.Number & " has occurred: " & ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
C# Example MySql.Data.MySqlClient.MySqlConnection conn;
MySql.Data.MySqlClient.MySqlCommand cmd;
conn = new MySql.Data.MySqlClient.MySqlConnection();
cmd = new MySql.Data.MySqlClient.MySqlCommand();
conn.ConnectionString = "server=127.0.0.1;uid=root;" +
"pwd=12345;database=test;";
try
{
conn.Open();
cmd.Connection = conn;
cmd.CommandText = "CREATE PROCEDURE add_emp(" +
"IN fname VARCHAR(20), IN lname VARCHAR(20), IN bday DATETIME, OUT empno INT) " +
"BEGIN INSERT INTO emp(first_name, last_name, birthdate) " +
"VALUES(fname, lname, DATE(bday)); SET empno = LAST_INSERT_ID(); END";
cmd.ExecuteNonQuery();
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
MessageBox.Show("Error " + ex.Number + " has occurred: " + ex.Message,
"Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
It should be noted that, unlike the command-line and GUI clients, you are not required to specify a special delimiter when creating stored procedures in Connector/NET.
To call a stored procedure using Connector/NET, create a
After the stored procedure is named, create one
After defining parameters, call the stored procedure by using
the Visual Basic Example Dim conn As New MySqlConnection
Dim cmd As New MySqlCommand
conn.ConnectionString = "server=127.0.0.1;" _
& "uid=root;" _
& "pwd=12345;" _
& "database=test"
Try
conn.Open()
cmd.Connection = conn
cmd.CommandText = "add_emp"
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add("?lname", 'Jones')
cmd.Parameters["?lname"].Direction = ParameterDirection.Input
cmd.Parameters.Add("?fname", 'Tom')
cmd.Parameters["?fname"].Direction = ParameterDirection.Input
cmd.Parameters.Add("?bday", #12/13/1977 2:17:36 PM#)
cmd.Parameters["?bday"].Direction = ParameterDirection.Input
cmd.Parameters.Add("?empno", MySqlDbType.Int32)
cmd.Parameters["?empno"].Direction = ParameterDirection.Output
cmd.ExecuteNonQuery()
MessageBox.Show(cmd.Parameters["?empno"].Value)
Catch ex As MySqlException
MessageBox.Show("Error " & ex.Number & " has occurred: " & ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
C# Example MySql.Data.MySqlClient.MySqlConnection conn;
MySql.Data.MySqlClient.MySqlCommand cmd;
conn = new MySql.Data.MySqlClient.MySqlConnection();
cmd = new MySql.Data.MySqlClient.MySqlCommand();
conn.ConnectionString = "server=127.0.0.1;uid=root;" +
"pwd=12345;database=test;";
try
{
conn.Open();
cmd.Connection = conn;
cmd.CommandText = "add_emp";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("?lname", "Jones");
cmd.Parameters["?lname"].Direction = ParameterDirection.Input;
cmd.Parameters.Add("?fname", "Tom");
cmd.Parameters["?fname"].Direction = ParameterDirection.Input;
cmd.Parameters.Add("?bday", DateTime.Parse("12/13/1977 2:17:36 PM"));
cmd.Parameters["?bday"].Direction = ParameterDirection.Input;
cmd.Parameters.Add("?empno", MySqlDbType.Int32);
cmd.Parameters["?empno"].Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery();
MessageBox.Show(cmd.Parameters["?empno"].Value);
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
MessageBox.Show("Error " + ex.Number + " has occurred: " + ex.Message,
"Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
Once the stored procedure is called, the values of output
parameters can be retrieved by using the
One common use for MySQL is the storage of binary data in
Data stored in a BLOB column can be accessed using Connector/NET and manipulated using client-side code. There are no special requirements for using Connector/NET with BLOB data.
Simple code examples will be presented within this section,
and a full sample application can be found in the
The first step is using MySQL with BLOB data is to configure the server. Let's start by creating a table to be accessed. In my file tables, I usually have four columns: an AUTO_INCREMENT column of appropriate size (UNSIGNED SMALLINT) to serve as a primary key to identify the file, a VARCHAR column that stores the filename, an UNSIGNED MEDIUMINT column that stores the size of the file, and a MEDIUMBLOB column that stores the file itself. For this example, I will use the following table definition: CREATE TABLE file( file_id SMALLINT UNSIGNED AUTO_INCREMENT NOT NULL PRIMARY KEY, file_name VARCHAR(64) NOT NULL, file_size MEDIUMINT UNSIGNED NOT NULL, file MEDIUMBLOB NOT NULL); After creating a table, you may need to modify the max_allowed_packet system variable. This variable determines how large of a packet (i.e. a single row) can be sent to the MySQL server. By default, the server will only accept a maximum size of 1 meg from our client application. If you do not intend to exceed 1 meg, this should be fine. If you do intend to exceed 1 meg in your file transfers, this number has to be increased.
The max_allowed_packet option can be modified using MySQL
Administrator's Startup Variables screen. Adjust the Maximum
allowed option in the Memory section of the Networking tab to
an appropriate setting. After adjusting the value, click the
button and restart the
server using the Try to be conservative when setting max_allowed_packet, as transfers of BLOB data can take some time to complete. Try to set a value that will be adequate for your intended use and increase the value if necessary.
To write a file to a database we need to convert the file to a
byte array, then use the byte array as a parameter to an
The following code opens a file using a FileStream object,
reads it into a byte array, and inserts it into the
Visual Basic Example Dim conn As New MySqlConnection
Dim cmd As New MySqlCommand
Dim SQL As String
Dim FileSize As UInt32
Dim rawData() As Byte
Dim fs As FileStream
conn.ConnectionString = "server=127.0.0.1;" _
& "uid=root;" _
& "pwd=12345;" _
& "database=test"
Try
fs = New FileStream("c:\image.png", FileMode.Open, FileAccess.Read)
FileSize = fs.Length
rawData = New Byte(FileSize) {}
fs.Read(rawData, 0, FileSize)
fs.Close()
conn.Open()
SQL = "INSERT INTO file VALUES(NULL, ?FileName, ?FileSize, ?File)"
cmd.Connection = conn
cmd.CommandText = SQL
cmd.Parameters.Add("?FileName", strFileName)
cmd.Parameters.Add("?FileSize", FileSize)
cmd.Parameters.Add("?File", rawData)
cmd.ExecuteNonQuery()
MessageBox.Show("File Inserted into database successfully!", _
"Success!", MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
conn.Close()
Catch ex As Exception
MessageBox.Show("There was an error: " & ex.Message, "Error", _
MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
C# Example MySql.Data.MySqlClient.MySqlConnection conn;
MySql.Data.MySqlClient.MySqlCommand cmd;
conn = new MySql.Data.MySqlClient.MySqlConnection();
cmd = new MySql.Data.MySqlClient.MySqlCommand();
string SQL;
UInt32 FileSize;
byte[] rawData;
FileStream fs;
conn.ConnectionString = "server=127.0.0.1;uid=root;" +
"pwd=12345;database=test;";
try
{
fs = new FileStream(@"c:\image.png", FileMode.Open, FileAccess.Read);
FileSize = fs.Length;
rawData = new byte[FileSize];
fs.Read(rawData, 0, FileSize);
fs.Close();
conn.Open();
SQL = "INSERT INTO file VALUES(NULL, ?FileName, ?FileSize, ?File)";
cmd.Connection = conn;
cmd.CommandText = SQL;
cmd.Parameters.Add("?FileName", strFileName);
cmd.Parameters.Add("?FileSize", FileSize);
cmd.Parameters.Add("?File", rawData);
cmd.ExecuteNonQuery();
MessageBox.Show("File Inserted into database successfully!",
"Success!", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
conn.Close();
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
MessageBox.Show("Error " + ex.Number + " has occurred: " + ex.Message,
"Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
The
After assigning the byte array as a parameter of the
Once a file is loaded into the
The following code retrieves a row from the
Visual Basic Example Dim conn As New MySqlConnection
Dim cmd As New MySqlCommand
Dim myData As MySqlDataReader
Dim SQL As String
Dim rawData() As Byte
Dim FileSize As UInt32
Dim fs As FileStream
conn.ConnectionString = "server=127.0.0.1;" _
& "uid=root;" _
& "pwd=12345;" _
& "database=test"
SQL = "SELECT file_name, file_size, file FROM file"
Try
conn.Open()
cmd.Connection = conn
cmd.CommandText = SQL
myData = cmd.ExecuteReader
If Not myData.HasRows Then Throw New Exception("There are no BLOBs to save")
myData.Read()
FileSize = myData.GetUInt32(myData.GetOrdinal("file_size"))
rawData = New Byte(FileSize) {}
myData.GetBytes(myData.GetOrdinal("file"), 0, rawData, 0, FileSize)
fs = New FileStream("C:\newfile.png", FileMode.OpenOrCreate, FileAccess.Write)
fs.Write(rawData, 0, FileSize)
fs.Close()
MessageBox.Show("File successfully written to disk!", "Success!", MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
myData.Close()
conn.Close()
Catch ex As Exception
MessageBox.Show("There was an error: " & ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
C# Example MySql.Data.MySqlClient.MySqlConnection conn;
MySql.Data.MySqlClient.MySqlCommand cmd;
MySql.Data.MySqlClient.MySqlDataReader myData;
conn = new MySql.Data.MySqlClient.MySqlConnection();
cmd = new MySql.Data.MySqlClient.MySqlCommand();
string SQL;
UInt32 FileSize;
byte[] rawData;
FileStream fs;
conn.ConnectionString = "server=127.0.0.1;uid=root;" +
"pwd=12345;database=test;";
SQL = "SELECT file_name, file_size, file FROM file";
try
{
conn.Open();
cmd.Connection = conn;
cmd.CommandText = SQL;
myData = cmd.ExecuteReader();
if (! myData.HasRows)
throw new Exception("There are no BLOBs to save");
myData.Read();
FileSize = myData.GetUInt32(myData.GetOrdinal("file_size"));
rawData = new byte[FileSize];
myData.GetBytes(myData.GetOrdinal("file"), 0, rawData, 0, FileSize);
fs = new FileStream(@"C:\newfile.png", FileMode.OpenOrCreate, FileAccess.Write);
fs.Write(rawData, 0, FileSize);
fs.Close();
MessageBox.Show("File successfully written to disk!",
"Success!", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
myData.Close();
conn.Close();
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
MessageBox.Show("Error " + ex.Number + " has occurred: " + ex.Message,
"Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
After connecting, the contents of the
The Crystal Reports is a common tool used by Windows application developers to perform reporting and document generation. In this section we will show how to use Crystal Reports XI with MySQL and Connector/NET. When creating a report in Crystal Reports there are two options for accessing the MySQL data while designing your report. The first option is to use Connector/ODBC as an ADO data source when designing your report. You will be able to browse your database and choose tables and fields using drag and drop to build your report. The disadvantage of this approach is that additional work must be performed within your application to produce a dataset that matches the one expected by your report. The second option is to create a dataset in VB.NET and save it as XML. This XML file can then be used to design a report. This works quite well when displaying the report in your application, but is less versatile at design time because you must choose all relevant columns when creating the dataset. If you forget a column you must re-create the dataset before the column can be added to the report. The following code can be used to create a dataset from a query and write it to disk: Visual Basic Example Dim myData As New DataSet
Dim conn As New MySqlConnection
Dim cmd As New MySqlCommand
Dim myAdapter As New MySqlDataAdapter
conn.ConnectionString = "server=127.0.0.1;" _
& "uid=root;" _
& "pwd=12345;" _
& "database=world"
Try
conn.Open()
cmd.CommandText = "SELECT city.name AS cityName, city.population AS CityPopulation, " _
& "country.name, country.population, country.continent " _
& "FROM country, city ORDER BY country.continent, country.name"
cmd.Connection = conn
myAdapter.SelectCommand = cmd
myAdapter.Fill(myData)
myData.WriteXml("C:\dataset.xml", XmlWriteMode.WriteSchema)
Catch ex As Exception
MessageBox.Show(ex.Message, "Report could not be created", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
C# Example DataSet myData = new DataSet();
MySql.Data.MySqlClient.MySqlConnection conn;
MySql.Data.MySqlClient.MySqlCommand cmd;
MySql.Data.MySqlClient.MySqlDataAdapter myAdapter;
conn = new MySql.Data.MySqlClient.MySqlConnection();
cmd = new MySql.Data.MySqlClient.MySqlCommand();
myAdapter = new MySql.Data.MySqlClient.MySqlDataAdapter();
conn.ConnectionString = "server=127.0.0.1;uid=root;" +
"pwd=12345;database=test;";
try
{
cmd.CommandText = "SELECT city.name AS cityName, city.population AS CityPopulation, " +
"country.name, country.population, country.continent " +
"FROM country, city ORDER BY country.continent, country.name";
cmd.Connection = conn;
myAdapter.SelectCommand = cmd;
myAdapter.Fill(myData);
myData.WriteXml(@"C:\dataset.xml", XmlWriteMode.WriteSchema);
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
MessageBox.Show(ex.Message, "Report could not be created",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
The resulting XML file can be used as an ADO.NET XML datasource when designing your report. If you choose to design your reports using Connector/ODBC, it can be downloaded from dev.mysql.com. For most purposes the Standard Report wizard should help with the initial creation of a report. To start the wizard, open Crystal Reports and choose the New > Standard Report option from the File menu. The wizard will first prompt you for a data source. If you are using Connector/ODBC as your data source, use the OLEDB provider for ODBC option from the OLE DB (ADO) tree instead of the ODBC (RDO) tree when choosing a data source. If using a saved dataset, choose the ADO.NET (XML) option and browse to your saved dataset. The remainder of the report creation process is done automatically by the wizard. After the report is created, choose the Report Options... entry of the File menu. Un-check the Save Data With Report option. This prevents saved data from interfering with the loading of data within our application. To display a report we first populate a dataset with the data needed for the report, then load the report and bind it to the dataset. Finally we pass the report to the crViewer control for display to the user. The following references are needed in a project that displays a report:
The following code assumes that you created your report using
a dataset saved using the code shown in
Section 23.2.5.5.2, “Creating a Data Source”,
and have a crViewer control on your form named
Visual Basic Example Imports CrystalDecisions.CrystalReports.Engine
Imports System.Data
Imports MySql.Data.MySqlClient
Dim myReport As New ReportDocument
Dim myData As New DataSet
Dim conn As New MySqlConnection
Dim cmd As New MySqlCommand
Dim myAdapter As New MySqlDataAdapter
conn.ConnectionString = _
"server=127.0.0.1;" _
& "uid=root;" _
& "pwd=12345;" _
& "database=test"
Try
conn.Open()
cmd.CommandText = "SELECT city.name AS cityName, city.population AS CityPopulation, " _
& "country.name, country.population, country.continent " _
& "FROM country, city ORDER BY country.continent, country.name"
cmd.Connection = conn
myAdapter.SelectCommand = cmd
myAdapter.Fill(myData)
myReport.Load(".\world_report.rpt")
myReport.SetDataSource(myData)
myViewer.ReportSource = myReport
Catch ex As Exception
MessageBox.Show(ex.Message, "Report could not be created", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
C# Example using CrystalDecisions.CrystalReports.Engine;
using System.Data;
using MySql.Data.MySqlClient;
ReportDocument myReport = new ReportDocument();
DataSet myData = new DataSet();
MySql.Data.MySqlClient.MySqlConnection conn;
MySql.Data.MySqlClient.MySqlCommand cmd;
MySql.Data.MySqlClient.MySqlDataAdapter myAdapter;
conn = new MySql.Data.MySqlClient.MySqlConnection();
cmd = new MySql.Data.MySqlClient.MySqlCommand();
myAdapter = new MySql.Data.MySqlClient.MySqlDataAdapter();
conn.ConnectionString = "server=127.0.0.1;uid=root;" +
"pwd=12345;database=test;";
try
{
cmd.CommandText = "SELECT city.name AS cityName, city.population AS CityPopulation, " +
"country.name, country.population, country.continent " +
"FROM country, city ORDER BY country.continent, country.name";
cmd.Connection = conn;
myAdapter.SelectCommand = cmd;
myAdapter.Fill(myData);
myReport.Load(@".\world_report.rpt");
myReport.SetDataSource(myData);
myViewer.ReportSource = myReport;
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
MessageBox.Show(ex.Message, "Report could not be created",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
A new dataset it generated using the same query used to generate the previously saved dataset. Once the dataset is filled, a ReportDocument is used to load the report file and bind it to the dataset. The ReportDocument is the passed as the ReportSource of the crViewer. This same approach is taken when a report is created from a single table using Connector/ODBC. The dataset replaces the table used in the report and the report is displayed properly. When a report is created from multiple tables using Connector/ODBC, a dataset with multiple tables must be created in our application. This allows each table in the report data source to be replaced with a report in the dataset.
We populate a dataset with multiple tables by providing
multiple SELECT `country`.`Name`, `country`.`Continent`, `country`.`Population`, `city`.`Name`, `city`.`Population` FROM `world`.`country` `country` LEFT OUTER JOIN `world`.`city` `city` ON `country`.`Code`=`city`.`CountryCode` ORDER BY `country`.`Continent`, `country`.`Name`, `city`.`Name`
This query is converted to two Visual Basic Example Imports CrystalDecisions.CrystalReports.Engine
Imports System.Data
Imports MySql.Data.MySqlClient
Dim myReport As New ReportDocument
Dim myData As New DataSet
Dim conn As New MySqlConnection
Dim cmd As New MySqlCommand
Dim myAdapter As New MySqlDataAdapter
conn.ConnectionString = "server=127.0.0.1;" _
& "uid=root;" _
& "pwd=12345;" _
& "database=world"
Try
conn.Open()
cmd.CommandText = "SELECT name, population, countrycode FROM city ORDER BY countrycode, name; " _
& "SELECT name, population, code, continent FROM country ORDER BY continent, name"
cmd.Connection = conn
myAdapter.SelectCommand = cmd
myAdapter.Fill(myData)
myReport.Load(".\world_report.rpt")
myReport.Database.Tables(0).SetDataSource(myData.Tables(0))
myReport.Database.Tables(1).SetDataSource(myData.Tables(1))
myViewer.ReportSource = myReport
Catch ex As Exception
MessageBox.Show(ex.Message, "Report could not be created", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
C# Example using CrystalDecisions.CrystalReports.Engine;
using System.Data;
using MySql.Data.MySqlClient;
ReportDocument myReport = new ReportDocument();
DataSet myData = new DataSet();
MySql.Data.MySqlClient.MySqlConnection conn;
MySql.Data.MySqlClient.MySqlCommand cmd;
MySql.Data.MySqlClient.MySqlDataAdapter myAdapter;
conn = new MySql.Data.MySqlClient.MySqlConnection();
cmd = new MySql.Data.MySqlClient.MySqlCommand();
myAdapter = new MySql.Data.MySqlClient.MySqlDataAdapter();
conn.ConnectionString = "server=127.0.0.1;uid=root;" +
"pwd=12345;database=test;";
try
{
cmd.CommandText = "SELECT name, population, countrycode FROM city ORDER " +
"BY countrycode, name;
It is important to order the This approach can cause performance problems because Crystal Reports must bind the tables together on the client-side, which will be slower than using a pre-saved dataset.
MySQL and the .NET languages handle date and time information
differently, with MySQL allowing dates that cannot be
represented by a .NET data type, such as ' In this section we will demonstrate how to properly handle date and time information when using Connector/NET.
The differences in date handling can cause problems for
developers who use invalid dates. Invalid MySQL dates cannot
be loaded into native .NET
Because of this issue, .NET The best solution to the date problem is to restrict users from entering invalid dates. This can be done on either the client or the server side.
Restricting invalid dates on the client side is as simple as
always using the .NET
Users of MySQL 5.0.2 and higher can use the new
Although it is strongly recommended that you avoid the use of
invalid dates within your .NET application, it is possible to
use invalid dates by means of the
The
To instruct Connector/NET to return a
Allow Zero Datetime=True
Please note that the use of the
Because of the known issues, the best recommendation is still to use only valid dates in your application.
The .NET
When using a Visual Basic Example If Not myReader.IsDBNull(myReader.GetOrdinal("mytime")) Then
myTime = myReader.GetDateTime(myReader.GetOrdinal("mytime"))
Else
myTime = DateTime.MinValue
End If
C# Example if (! myReader.IsDBNull(myReader.GetOrdinal("mytime")))
myTime = myReader.GetDateTime(myReader.GetOrdinal("mytime"));
else
myTime = DateTime.MinValue;
The developers of Connector/NET greatly value the input of our users in the software development process. If you find Connector/NET lacking some feature important to you, or if you discover a bug and need to file a bug report, please use the instructions in Section 1.8, “How to Report Bugs or Problems”.
If you encounter difficulties or problems with Connector/NET, contact the Connector/NET community Section 23.2.6.1, “Connector/NET Community Support”.
You should first try to execute the same SQL statements and
commands from the mysql client program or
from If reporting a problem, you should ideally include the following information with the email:
Remember that the more information you can supply to us, the more likely it is that we can fix the problem. If you believe the problem to be a bug, then you must report the bug through http://bugs.mysql.com/. The Connector/NET Change History (Changelog) is located with the main Changelog for MySQL. See Section E.4, “Connector/NET Change History”. The MySQL Visual Studio Plugin is a DDEX provider; a plug-in for Visual Studio 2005 that allows developers to maintain database structures, and supports built-in data-driven application development tools. The current version of the MySQL Visual Studio Plugin includes only database maintenance tools. Data-driven application development tools are not supported. The MySQL DDEX Provider operates as a standard extension to the Visual Studio Data Designer functionality available through the Server Explorer menu of Visual Studio 2005, and enables developers to create database objects and data within a MySQL database. The MySQL Visual Studio Plugin is designed to work with MySQL version 5.0, but is also compatible with MySQL 4.1.1 and provides limited compatibility with MySQL 5.1. The MySQL Visual Studio Plugin requires one of Visual Studio 2005 Standard, Professional or Team Developer Edition to be installed. Other editions of Visual Studio 2005 are not supported. NoteStarting with Connector/NET 5.1.2, the Visual Studio Plugin is included in the installation. If you have installed Connector/NET 5.1.2, then you do not need to separately install the Visual Studio Plugin. Here is the list of components that should already be installed before starting the installation of the MySQL Visual Studio Plugin:
NoteWhen installing Connector/NET you must ensure that the connector is installed into the Global Assembly Cache (GAC). The Connector/NET installer handles this for you automatically, but in a custom installation the option may have been disabled. The user used to connect to the MySQL server must have the following privileges to use the functionality provided by the MySQL Visual Studio Plugin:
The MySQL Visual Studio Plugin is delivered as a MSI package that can be used to install, uninstall or reinstall the Provider. If you are not using Windows XP or Windows Server 2003 you upgrade the Windows Installer system to the latest version (see http://support.microsoft.com/default.aspx?scid=kb;EN-US;292539 for details).
The MSI-package is named
To uninstall the MySQL Visual Studio Plugin, you can use either Add/Remove Programs component of the Control Panel or the same MSI-package. Choose the Remove option, and the Provider will be uninstalled automatically. To repair the Provider, right click the MSI-package and choose the option. The MySQL Visual Studio Plugin will be repaired automatically. The installation package includes the following files:
To install the Provider manually, copy all files of the installation package in a desired folder, then set the full path to the Provider assembly as a value of the CodeBase entry. For example: [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\8.0\Packages\{79A115C9-B133-4891-9E7B-242509DAD272}]@="MySql.Data.VisualStudio.MySqlDataProviderPackage"
"InprocServer32"="C:\\WINNT\\system32\\mscoree.dll"
"Class"="MySql.Data.VisualStudio.MySqlDataProviderPackage"
"CodeBase"="C:\\MySqlDdexProvider\\MySql.VisualStudio.dll"
Then import information from the Register.reg file to the registry by clicking of the file. At the confirmation dialog choose Yes. Next you must run the command devenv.exe /setup within a Command Prompt to rebuild the Visual Studio command table. Once the MySQL Visual Studio Plugin 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:
After a connection is successfully established, all the connection settings are saved. When you next open Visual Studio, the connection to the MySQL server will appear within Server Explorer so that you can re-establish a connection to the MySQL server. To modify and delete a connection, use the context menu for the corresponding node. You can modify any of the settings just by overwriting the existing values with new ones. Note that a connection should be modified or deleted only if no active editor for it's objects is opened. Otherwise your data could be lost. To work with a MySQL server using the MySQL Visual Studio Plugin, open the Visual Studio 2005, open the Server Explorer, and select the required connection. The working area of the MySQL Visual Studio Plugin consists of three parts. ![]()
The Table Editor can be accessed through a mouse action on table-type node of Server Explorer. To create a new table, right click on the Tables node (under the connection node) and choose the command from a context menu. To modify an existing table, double click on a node of the table you wish to modify, or right click on this node and choose the command from a context menu. Either of the commands opens the Table Editor. ![]() The MySQL Visual Studio Plugin Table Editor is implemented in a similar fashion to the standard Query Browser Table Editor, but with minor differences. The Table Editor consists of the following parts:
To save changes you have made in the Table Editor, use either Save or Save All buttons of the Visual Studio main toolbar, or just press Ctrl+S. Before changes are saved, a confirmation dialog will be displayed to confirm that you want to update the corresponding object within the MySQL database. 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 properties of an individual column, select the column using the mouse. Alternatively, you can move through the grid using Tab and Shift+Tab keys.
Index management is performed via the Indexes tab.
You cannot change a table column to an index column using drag and drop. Instead, you can add new index columns to a table and set their table columns by using the embedded editor within the Indexes tab Foreign Key management is performed via the Foreign Keys tab.
NoteIf changed values are for some reason inconsistent and cause the second query to fail, all affected foreign keys will be dropped. If this is the case, the MySQL Visual Studio Plugin will mark them as new in the Table Editor, and you will have to recreate them later. But if you close the Table Editor without saving, these foreign keys will be lost. The Column Details tab can be used to set column options. Besides the main column properties that are presented in the Column Editor, in the Column Details tab you can set two additional properties options: the character set and the collation sequence. There is no separate tab for table options and advanced options. All table options can be browsed and changed using the Properties window of Visual Studio 2005. The following table properties can be set:
Some of these properties can have arbitrary text values, others accept values from a predefined set. The properties Schema and Server are read only. The Table Data Editor, allows a user to browse, create and edit data of tables. The Table Data Editor is implemented as a simple data grid with auto generated columns. To access the Table Data Editor, right click on a node representing the table or view in Server Explorer. From the nodes context menu, choose the or command. For tables and updatable views, this command opens the Table Data Editor in edit mode. For non-updatable views, this command opens the Table Data Editor in read-only mode. When in the edit mode, you can modify table data by modifying the displayed table contents directly. To add a row, set desired values in the last row of the grid. To modify values, set new values in appropriate cells. To delete a row, select it by clicking on the selector column at the left of the grid, then press the button. To save changes you have made in the Table Data Editor, use either or buttons of the Visual Studio main toolbar, or just press Ctrl+S. A confirmation dialog will confirm whether you want the changes saved to the database. To create a new view, right click the Views node under the connection node in Server Explorer. From the nodes context menu, choose the command. This command opens the SQL Editor. To modify an existing view, double click on a node of the view you wish to modify, or right click on this node and choose the command from a context menu. Either of the commands opens the SQL Editor. To create or alter the view definition using SQL Editor, type the appropriate SQL statement in the SQL Editor. Note
You should enter only the defining statement itself, without
the All other view properties can be set in the Properties window. These properties are:
Some of these properties can have arbitrary text values, others accept values from a predefined set. The properties Is Updatable, Schema and Server are readonly. To save changes you have made, use either or buttons of the Visual Studio main toolbar, or just press Ctrl+S. A confirmation dialog will confirm whether you want the changes saved to the database. To create a new stored procedure, right click the Stored Procedures node under the connection node in Server Explorer. From the nodes context menu, choose the command. This command opens the SQL Editor. 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 command. To modify an existing stored routine (procedure or function), double click on a node of the routine you wish to modify, or right click on this node and choose the command from a 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:
Some of these properties can have arbitrary text values, others accept values only from a predefined set.
Also you can set all the options directly in the SQL Editor,
using the standard Note
You should never add the The properties Name, Schema and Server in the Properties window are read-only. Set or change the procedure name in the SQL editor. To save changes you have made, use either or buttons of the Visual Studio main toolbar, or just press Ctrl+S. A confirmation dialog will confirm whether you want the changes saved to the database.. To create a new trigger, right click on a node of a table for which you wish to add a trigger. From the node's context menu, choose the command. This command opens the SQL Editor. To modify an existing trigger, double click on a node of the trigger you wish to modify, or right click on this node and choose the command from a 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
You should enter only the trigger statement, that is the part
of the All other trigger properties are set in the Properties window. These properties are:
Some of these properties can have arbitrary text values, others accept values only from a predefined set. The properties Event Table, Schema and Server in the Properties window are read-only. To save changes you have made, use either or buttons of the Visual Studio main toolbar, or just press Ctrl+S. A confirmation dialog will confirm whether you want the changes saved to the database. 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 command. This command opens the UDF Editor. To modify an existing UDF, double click on a node of the UDF you wish to modify, or right click on this node and choose the Alter UDF command from a context menu. Either of the commands opens the UDF Editor. The UDF editor allows you to set the following properties through the properties panel:
The property Server in the Properties window is read-only. To save changes you have made, use either or buttons of the Visual Studio main toolbar, or just press Ctrl+S. A confirmation dialog will confirm whether you want the changes saved to the database. Tables, views, stored routines, triggers, an UDFs can be dropped with the appropriate command from its context menu: , , , , . You will be asked to confirm the execution of the corresponding drop query in a confirmation dialog. Dropping of multiple objects is not supported. Tables, views, stored procedures and functions can be cloned with the appropriate command from its context menu: , , . 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. To save the cloned object, use either or buttons of the Visual Studio main toolbar, or just press Ctrl+S. A confirmation dialog will confirm whether you want the changes saved to the database. If you have a comment, or if you discover a bug, please, use our MySQL bug tracking system (http://bugs.mysql.com) to report problem or add your suggestion. Questions
Questions and Answers 24.3.4.1.1: When creating a connection, typing the connection details causes the connection window to immediately close. There are known issues with versions of Connector/NET earlier than 5.0.2. Connector/NET 1.0.x is known not to work. If you have any of these versions installed, or have previously upgraded from an earlier version, uninstall Connector/NET completely and then install Connector/NET 5.0.2. MySQL provides connectivity for client applications developed in the Java programming language via a JDBC driver, which is called MySQL Connector/J. MySQL Connector/J is a JDBC-3.0 Type 4 driver, which means that is pure Java, implements version 3.0 of the JDBC specification, and communicates directly with the MySQL server using the MySQL protocol. Although JDBC is useful by itself, we would hope that if you are not familiar with JDBC that after reading the first few sections of this manual, that you would avoid using naked JDBC for all but the most trivial problems and consider using one of the popular persistence frameworks such as Hibernate, Spring's JDBC templates or Ibatis SQL Maps to do the majority of repetitive work and heavier lifting that is sometimes required with JDBC. This section is not designed to be a complete JDBC tutorial. If you need more information about using JDBC you might be interested in the following online tutorials that are more in-depth than the information presented here:
Key topics:
There are currently four versions of MySQL Connector/J available:
The current recommended version for Connector/J is 5.0. This guide covers all three connector versions, with specific notes given where a setting applies to a specific option. MySQL Connector/J supports Java-2 JVMs, including:
If you are building Connector/J from source using the source distribution (see Section 23.4.2.4, “Installing from the Development Source Tree”) then you must use JDK 1.4.x or newer to compiler the Connector package. MySQL Connector/J does not support JDK-1.1.x or JDK-1.0.x.
Because of the implementation of
Caching functionality provided by Connector/J 3.1.0 or newer is
also not available on JVMs older than 1.4.x, as it relies on
You can install the Connector/J package using two methods, using
either the binary or source distribution. The binary distribution
provides the easiest methods for installation; the source
distribution enables you to customize your installation further.
With either solution, you must manually add the Connector/J
location to your Java
The easiest method of installation is to use the binary
distribution of the Connector/J package. The binary distribution
is available either as a Tar/Gzip or Zip file which you must
extract to a suitable location and then optionally make the
information about the package available by changing your
MySQL Connector/J is distributed as a .zip or .tar.gz archive
containing the sources, the class files, and the JAR archive
named
Starting with Connector/J 3.1.9, the
You should not use the debug build of the driver unless
instructed to do so when reporting a problem ors bug to MySQL
AB, as it is not designed to be run in production environments,
and will have adverse performance impact when used. The debug
binary also depends on the Aspect/J runtime library, which is
located in the You will need to use the appropriate graphical or command-line utility to extract the distribution (for example, WinZip for the .zip archive, and tar for the .tar.gz archive). Because there are potentially long filenames in the distribution, we use the GNU tar archive format. You will need to use GNU tar (or an application that understands the GNU tar archive format) to unpack the .tar.gz variant of the distribution.
Once you have extracted the distribution archive, you can
install the driver by placing
If you are going to use the driver with the JDBC DriverManager,
you would use
You can set the
For example, under a C shell (csh, tcsh) you would add the
Connector/J driver to your shell> setenv CLASSPATH /path/mysql-connector-java-[ver]-bin.jar:$CLASSPATH Or with a Bourne-compatible shell (sh, ksh, bash): export set CLASSPATH=/path/mysql-connector-java-[ver]-bin.jar:$CLASSPATH Within Windows 2000, Windows XP and Windows Server 2003, you must set the environment variable through the System control panel.
If you want to use MySQL Connector/J with an application server
such as Tomcat or JBoss, you will have to read your vendor's
documentation for more information on how to configure
third-party class libraries, as most application servers ignore
the If you are developing servlets or JSPs, and your application server is J2EE-compliant, you can put the driver's .jar file in the WEB-INF/lib subdirectory of your webapp, as this is a standard location for third party class libraries in J2EE web applications.
You can also use the MysqlDataSource or
MysqlConnectionPoolDataSource classes in the
The various MysqlDataSource classes support the following parameters (through standard set mutators):
MySQL AB tries to keep the upgrade process as easy as possible, however as is the case with any software, sometimes changes need to be made in new versions to support new features, improve existing functionality, or comply with new standards. This section has information about what users who are upgrading from one version of Connector/J to another (or to a new version of the MySQL server, with respect to JDBC functionality) should be aware of. Connector/J 3.1 is designed to be backward-compatible with Connector/J 3.0 as much as possible. Major changes are isolated to new functionality exposed in MySQL-4.1 and newer, which includes Unicode character sets, server-side prepared statements, SQLState codes returned in error messages by the server and various performance enhancements that can be enabled or disabled via configuration properties.
CautionYou should read this section only if you are interested in helping us test our new code. If you just want to get MySQL Connector/J up and running on your system, you should use a standard release distribution. To install MySQL Connector/J from the development source tree, make sure that you have the following prerequisites:
The Subversion source code repository for MySQL Connector/J is located at http://svn.mysql.com/svnpublic/connector-j. In general, you should not check out the entire repository because it contains every branch and tag for MySQL Connector/J and is quite large. To check out and compile a specific branch of MySQL Connector/J, follow these steps:
Examples of using Connector/J are located throughout this document, this section provides a summary and links to these examples.
This section of the manual contains reference material for MySQL Connector/J, some of which is automatically generated during the Connector/J build process.
The name of the class that implements java.sql.Driver in MySQL
Connector/J is The JDBC URL format for MySQL Connector/J is as follows, with items in square brackets ([, ]) being optional: jdbc:mysql://[host][,failoverhost...][:port]/[database] » [?propertyName1][=propertyValue1][&propertyName2][=propertyValue2]... If the hostname is not specified, it defaults to 127.0.0.1. If the port is not specified, it defaults to 3306, the default port number for MySQL servers. jdbc:mysql://[host:port],[host:port].../[database] » [?propertyName1][=propertyValue1][&propertyName2][=propertyValue2]...
If the database is not specified, the connection will be made
with no default database. In this case, you will need to either
call the
MySQL Connector/J has fail-over support. This allows the driver
to fail-over to any number of slave hosts and still perform
read-only queries. Fail-over only happens when the connection is
in an The fail-over functionality has the following behavior:
In either case, whenever you are connected to a "failed-over" server, the connection will be set to read-only state, so queries that would modify data will have exceptions thrown (the query will never be processed by the MySQL server). Configuration properties define how Connector/J will make a connection to a MySQL server. Unless otherwise noted, properties can be set for a DataSource object or for a Connection object. Configuration Properties can be set in one of the following ways:
The properties are listed in the following tables. Connection/Authentication.
Networking.
High Availability and Clustering.
Security.
Performance Extensions.
Debugging/Profiling.
Miscellaneous.
Connector/J also supports access to MySQL via named pipes on
Windows NT/2000/XP using the
NamedPipeSocketFactory as a plugin-socket
factory via the socketFactory property. If
you don't use a namedPipePath property, the
default of '\\.\pipe\MySQL' will be used. If you use the
socketFactory=com.mysql.jdbc.NamedPipeSocketFactory
Named pipes only work when connecting to a MySQL server on the same physical machine as the one the JDBC driver is being used on. In simple performance tests, it appears that named pipe access is between 30%-50% faster than the standard TCP/IP access.
You can create your own socket factories by following the
example code in
MySQL Connector/J passes all of the tests in the publicly-available version of Sun's JDBC compliance test suite. However, in many places the JDBC specification is vague about how certain functionality should be implemented, or the specification allows leeway in implementation. This section gives details on a interface-by-interface level about how certain implementation decisions may affect how you use MySQL Connector/J.
MySQL Connector/J is flexible in the way it handles conversions between MySQL data types and Java data types. In general, any MySQL data type can be converted to a java.lang.String, and any numerical type can be converted to any of the Java numerical types, although round-off, overflow, or loss of precision may occur.
Starting with Connector/J 3.1.0, the JDBC driver will issue
warnings or throw DataTruncation exceptions as is required by
the JDBC specification unless the connection was configured not
to do so by using the property
jdbcCompliantTruncation and setting it to
The conversions that are always guaranteed to work are listed in the following table: Connection Properties - Miscellaneous.
NoteRound-off, overflow or loss of precision may occur if you choose a Java numeric data type that has less precision or capacity than the MySQL data type you are converting to/from.
The MySQL Types to Java Types for ResultSet.getObject().
All strings sent from the JDBC driver to the server are
converted automatically from native Java Unicode form to the
client character encoding, including all queries sent via
Prior to MySQL Server 4.1, Connector/J supported a single
character encoding per connection, which could either be
automatically detected from the server configuration, or could
be configured by the user through the
Starting with MySQL Server 4.1, Connector/J supports a single
character encoding between client and server, and any number of
character encodings for data returned by the server to the
client in
The character encoding between client and server is
automatically detected upon connection. The encoding used by the
driver is specified on the server via the
To override the automatically-detected encoding on the client
side, use the When specifying character encodings on the client side, Java-style names should be used. The following table lists Java-style names for MySQL character sets: MySQL to Java Encoding Name Translations.
WarningDo not issue the query 'set names' with Connector/J, as the driver will not detect that the character set has changed, and will continue to use the character set detected during the initial connection setup.
To allow multiple character sets to be sent from the client, the
UTF-8 encoding should be used, either by configuring
SSL in MySQL Connector/J encrypts all data (other than the initial handshake) between the JDBC driver and the server. The performance penalty for enabling SSL is an increase in query processing time between 35% and 50%, depending on the size of the query, and the amount of data it returns. For SSL Support to work, you must have the following:
You will first need to import the MySQL server CA Certificate
into a Java truststore. A sample MySQL server CA Certificate is
located in the
To use Java's keytool to create a truststore
in the current directory , and import the server's CA
certificate ( shell> keytool -import -alias mysqlServerCACert \
-file cacert.pem -keystore truststoreKeytool will respond with the following information: Enter keystore password: *********
Owner: EMAILADDRESS=walrus@example.com, CN=Walrus,
O=MySQL AB, L=Orenburg, ST=Some-State, C=RU
Issuer: EMAILADDRESS=walrus@example.com, CN=Walrus,
O=MySQL AB, L=Orenburg, ST=Some-State, C=RU
Serial number: 0
Valid from:
Fri Aug 02 16:55:53 CDT 2002 until: Sat Aug 02 16:55:53 CDT 2003
Certificate fingerprints:
MD5: 61:91:A0:F2:03:07:61:7A:81:38:66:DA:19:C4:8D:AB
SHA1: 25:77:41:05:D5:AD:99:8C:14:8C:CA:68:9C:2F:B8:89:C3:34:4D:6C
Trust this certificate? [no]: yes
Certificate was added to keystoreYou will then need to generate a client certificate, so that the MySQL server knows that it is talking to a secure client: shell> keytool -genkey -keyalg rsa \
-alias mysqlClientCertificate -keystore keystore
Keytool will prompt you for the following information, and
create a keystore named You should respond with information that is appropriate for your situation: Enter keystore password: *********
What is your first and last name?
[Unknown]: Matthews
What is the name of your organizational unit?
[Unknown]: Software Development
What is the name of your organization?
[Unknown]: MySQL AB
What is the name of your City or Locality?
[Unknown]: Flossmoor
What is the name of your State or Province?
[Unknown]: IL
What is the two-letter country code for this unit?
[Unknown]: US
Is <CN=Matthews, OU=Software Development, O=MySQL AB,
L=Flossmoor, ST=IL, C=US> correct?
[no]: y
Enter key password for <mysqlClientCertificate>
(RETURN if same as keystore password):Finally, to get JSSE to use the keystore and truststore that you have generated, you need to set the following system properties when you start your JVM, replacing path_to_keystore_file with the full path to the keystore file you created, path_to_truststore_file with the path to the truststore file you created, and using the appropriate password values for each property. You can do this either on the command line: -Djavax.net.ssl.keyStore=path_to_keystore_file -Djavax.net.ssl.keyStorePassword=password -Djavax.net.ssl.trustStore=path_to_truststore_file -Djavax.net.ssl.trustStorePassword=password Or you can set the values directly within the application: System.setProperty("javax.net.ssl.keyStore","path_to_keystore_file");
System.setProperty("javax.net.ssl.keyStorePassword","password");
System.setProperty("javax.net.ssl.trustStore","path_to_truststore_file");
System.setProperty("javax.net.ssl.trustStorePassword","password");
You will also need to set useSSL to
You can test that SSL is working by turning on JSSE debugging (as detailed below), and look for the following key events: ...
*** ClientHello, v3.1
RandomCookie: GMT: 1018531834 bytes = { 199, 148, 180, 215, 74, 12, »
54, 244, 0, 168, 55, 103, 215, 64, 16, 138, 225, 190, 132, 153, 2, »
217, 219, 239, 202, 19, 121, 78 }
Session ID: {}
Cipher Suites: { 0, 5, 0, 4, 0, 9, 0, 10, 0, 18, 0, 19, 0, 3, 0, 17 }
Compression Methods: { 0 }
***
[write] MD5 and SHA1 hashes: len = 59
0000: 01 00 00 37 03 01 3D B6 90 FA C7 94 B4 D7 4A 0C ...7..=.......J.
0010: 36 F4 00 A8 37 67 D7 40 10 8A E1 BE 84 99 02 D9 6...7g.@........
0020: DB EF CA 13 79 4E 00 00 10 00 05 00 04 00 09 00 ....yN..........
0030: 0A 00 12 00 13 00 03 00 11 01 00 ...........
main, WRITE: SSL v3.1 Handshake, length = 59
main, READ: SSL v3.1 Handshake, length = 74
*** ServerHello, v3.1
RandomCookie: GMT: 1018577560 bytes = { 116, 50, 4, 103, 25, 100, 58, »
202, 79, 185, 178, 100, 215, 66, 254, 21, 83, 187, 190, 42, 170, 3, »
132, 110, 82, 148, 160, 92 }
Session ID: {163, 227, 84, 53, 81, 127, 252, 254, 178, 179, 68, 63, »
182, 158, 30, 11, 150, 79, 170, 76, 255, 92, 15, 226, 24, 17, 177, »
219, 158, 177, 187, 143}
Cipher Suite: { 0, 5 }
Compression Method: 0
***
%% Created: [Session-1, SSL_RSA_WITH_RC4_128_SHA]
** SSL_RSA_WITH_RC4_128_SHA
[read] MD5 and SHA1 hashes: len = 74
0000: 02 00 00 46 03 01 3D B6 43 98 74 32 04 67 19 64 ...F..=.C.t2.g.d
0010: 3A CA 4F B9 B2 64 D7 42 FE 15 53 BB BE 2A AA 03 :.O..d.B..S..*..
0020: 84 6E 52 94 A0 5C 20 A3 E3 54 35 51 7F FC FE B2 .nR..\ ..T5Q....
0030: B3 44 3F B6 9E 1E 0B 96 4F AA 4C FF 5C 0F E2 18 .D?.....O.L.\...
0040: 11 B1 DB 9E B1 BB 8F 00 05 00 ..........
main, READ: SSL v3.1 Handshake, length = 1712
...
JSSE provides debugging (to STDOUT) when you set the following
system property:
Starting with Connector/J 3.1.7, we've made available a variant
of the driver that will automatically send queries to a
read/write master, or a failover or round-robin loadbalanced set
of slaves based on the state of
An application signals that it wants a transaction to be
read-only by calling
To enable this functionality, use the "
Here is a short, simple example of how ReplicationDriver might be used in a standalone application. import java.sql.Connection;
import java.sql.ResultSet;
import java.util.Properties;
import com.mysql.jdbc.ReplicationDriver;
public class ReplicationDriverDemo {
public static void main(String[] args) throws Exception {
ReplicationDriver driver = new ReplicationDriver();
Properties props = new Properties();
// We want this for failover on the slaves
props.put("autoReconnect", "true");
// We want to load balance between the slaves
props.put("roundRobinLoadBalance", "true");
props.put("user", "foo");
props.put("password", "bar");
//
// Looks like a normal MySQL JDBC url, with a
// comma-separated list of hosts, the first
// being the 'master', the rest being any number
// of slaves that the driver will load balance against
//
Connection conn =
driver.connect("jdbc:mysql://master,slave1,slave2,slave3/test",
props);
//
// Perform read/write work on the master
// by setting the read-only flag to "false"
//
conn.setReadOnly(false);
conn.setAutoCommit(false);
conn.createStatement().executeUpdate("UPDATE some_table ....");
conn.commit();
//
// Now, do a query from a slave, the driver automatically picks one
// from the list
//
conn.setReadOnly(true);
ResultSet rs =
conn.createStatement().executeQuery("SELECT a,b FROM alt_table");
.......
}
}
The table below provides a mapping of the MySQL Error Numbers to
Table 23.1. Mapping of MySQL Error Numbers to SQLStates
This section provides some general JDBC background.
When you are using JDBC outside of an application server, the
The
The following section of Java code shows how you might
register MySQL Connector/J from the import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
// Notice, do not import com.mysql.jdbc.*
// or you will have problems!
public class LoadDriver {
public static void main(String[] args) {
try {
// The newInstance() call is a work around for some
// broken Java implementations
Class.forName("com.mysql.jdbc.Driver").newInstance();
} catch (Exception ex) {
// handle the error
}
}
After the driver has been registered with the
Example 23.1. Obtaining a connection from the
This example shows how you can obtain a
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
...
try {
Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost/test?" +
"user=monty&password=greatsqldb");
// Do something with the Connection
...
} catch (SQLException ex) {
// handle any errors
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
}
Once a
To create a
Once you have a
To update data in the database, use the
If you don't know ahead of time whether the SQL statement will
be a Example 23.2. Using java.sql.Statement to execute a // assume that conn is an already created JDBC connection
Statement stmt = null;
ResultSet rs = null;
try {
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT foo FROM bar");
// or alternatively, if you don't know ahead of time that
// the query will be a SELECT...
if (stmt.execute("SELECT foo FROM bar")) {
rs = stmt.getResultSet();
}
// Now do something with the ResultSet ....
} finally {
// it is a good idea to release
// resources in a finally{} block
// in reverse-order of their creation
// if they are no-longer needed
if (rs != null) {
try {
rs.close();
} catch (SQLException sqlEx) { // ignore }
rs = null;
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException sqlEx) { // ignore }
stmt = null;
}
}
Starting with MySQL server version 5.0 when used with
Connector/J 3.1.1 or newer, the
See Chapter 17, Stored Procedures and Functions, for more information on MySQL stored procedures.
Connector/J exposes stored procedure functionality through
JDBC's Note
Current versions of MySQL server do not return enough
information for the JDBC driver to provide result set
metadata for callable statements. This means that when using
The following example shows a stored procedure that returns
the value of Example 23.3. Stored Procedures CREATE PROCEDURE demoSp(IN inputParam VARCHAR(255), \
INOUT inOutParam INT)
BEGIN
DECLARE z INT;
SET z = inOutParam + 1;
SET inOutParam = z;
SELECT inputParam;
SELECT CONCAT('zyxw', inputParam);
END
To use the
Before version 3.0 of the JDBC API, there was no standard way
of retrieving key values from databases that supported auto
increment or identity columns. With older JDBC drivers for
MySQL, you could always use a MySQL-specific method on the
Example 23.8. Retrieving Statement stmt = null;
ResultSet rs = null;
try {
//
// Create a Statement instance that we can use for
// 'normal' result sets assuming you have a
// Connection 'conn' to a MySQL database already
// available
stmt = conn.createStatement(java.sql.ResultSet.TYPE_FORWARD_ONLY,
java.sql.ResultSet.CONCUR_UPDATABLE);
//
// Issue the DDL queries for the table for this example
//
stmt.executeUpdate("DROP TABLE IF EXISTS autoIncTutorial");
stmt.executeUpdate(
"CREATE TABLE autoIncTutorial ("
+ "priKey INT NOT NULL AUTO_INCREMENT, "
+ "dataField VARCHAR(64), PRIMARY KEY (priKey))");
//
// Insert one row that will generate an AUTO INCREMENT
// key in the 'priKey' field
//
stmt.executeUpdate(
"INSERT INTO autoIncTutorial (dataField) "
+ "values ('Can I Get the Auto Increment Field?')",
Statement.RETURN_GENERATED_KEYS);
//
// Example of using Statement.getGeneratedKeys()
// to retrieve the value of an auto-increment
// value
//
int autoIncKeyFromApi = -1;
rs = stmt.getGeneratedKeys();
if (rs.next()) {
autoIncKeyFromApi = rs.getInt(1);
} else {
// throw an exception from here
}
rs.close();
rs = null;
System.out.println("Key returned from getGeneratedKeys():"
+ autoIncKeyFromApi);
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException ex) {
// ignore
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException ex) {
// ignore
}
}
}
Example 23.9. Retrieving Statement stmt = null;
ResultSet rs = null;
try {
//
// Create a Statement instance that we can use for
// 'normal' result sets.
stmt = conn.createStatement();
//
// Issue the DDL queries for the table for this example
//
stmt.executeUpdate("DROP TABLE IF EXISTS autoIncTutorial");
stmt.executeUpdate(
"CREATE TABLE autoIncTutorial ("
+ "priKey INT NOT NULL AUTO_INCREMENT, "
+ "dataField VARCHAR(64), PRIMARY KEY (priKey))");
//
// Insert one row that will generate an AUTO INCREMENT
// key in the 'priKey' field
//
stmt.executeUpdate(
"INSERT INTO autoIncTutorial (dataField) "
+ "values ('Can I Get the Auto Increment Field?')");
//
// Use the MySQL LAST_INSERT_ID()
// function to do the same thing as getGeneratedKeys()
//
int autoIncKeyFromFunc = -1;
rs = stmt.executeQuery("SELECT LAST_INSERT_ID()");
if (rs.next()) {
autoIncKeyFromFunc = rs.getInt(1);
} else {
// throw an exception from here
}
rs.close();
System.out.println("Key returned from " +
"'SELECT LAST_INSERT_ID()': " +
autoIncKeyFromFunc);
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException ex) {
// ignore
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException ex) {
// ignore
}
}
}
Example 23.10. Retrieving Statement stmt = null;
ResultSet rs = null;
try {
//
// Create a Statement instance that we can use for
// 'normal' result sets as well as an 'updatable'
// one, assuming you have a Connection 'conn' to
// a MySQL database already available
//
stmt = conn.createStatement(java.sql.ResultSet.TYPE_FORWARD_ONLY,
java.sql.ResultSet.CONCUR_UPDATABLE);
//
// Issue the DDL queries for the table for this example
//
stmt.executeUpdate("DROP TABLE IF EXISTS autoIncTutorial");
stmt.executeUpdate(
"CREATE TABLE autoIncTutorial ("
+ "priKey INT NOT NULL AUTO_INCREMENT, "
+ "dataField VARCHAR(64), PRIMARY KEY (priKey))");
//
// Example of retrieving an AUTO INCREMENT key
// from an updatable result set
//
rs = stmt.executeQuery("SELECT priKey, dataField "
+ "FROM autoIncTutorial");
rs.moveToInsertRow();
rs.updateString("dataField", "AUTO INCREMENT here?");
rs.insertRow();
//
// the driver adds rows at the end
//
rs.last();
//
// We should now be on the row we just inserted
//
int autoIncKeyFromRS = rs.getInt("priKey");
rs.close();
rs = null;
System.out.println("Key returned for inserted row: "
+ autoIncKeyFromRS);
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException ex) {
// ignore
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException ex) {
// ignore
}
}
}
When you run the preceding example code, you should get the
following output: Key returned from
This section describes how to use Connector/J in several contexts. This section provides general background on J2EE concepts that pertain to use of Connector/J. Connection pooling is a technique of creating and managing a pool of connections that are ready for use by any thread that needs them. This technique of pooling connections is based on the fact that most applications only need a thread to have access to a JDBC connection when they are actively processing a transaction, which usually take only milliseconds to complete. When not processing a transaction, the connection would otherwise sit idle. Instead, connection pooling allows the idle connection to be used by some other thread to do useful work. In practice, when a thread needs to do work against a MySQL or other database with JDBC, it requests a connection from the pool. When the thread is finished using the connection, it returns it to the pool, so that it may be used by any other threads that want to use it.
When the connection is loaned out from the pool, it is used
exclusively by the thread that requested it. From a
programming point of view, it is the same as if your thread
called Connection pooling can greatly increase the performance of your Java application, while reducing overall resource usage. The main benefits to connection pooling are:
Remember that each connection to MySQL has overhead (memory, CPU, context switches, and so forth) on both the client and server side. Every connection limits how many resources there are available to your application as well as the MySQL server. Many of these resources will be used whether or not the connection is actually doing any useful work! Connection pools can be tuned to maximize performance, while keeping resource utilization below the point where your application will start to fail rather than just run slower. Luckily, Sun has standardized the concept of connection pooling in JDBC through the JDBC-2.0 Optional interfaces, and all major application servers have implementations of these APIs that work fine with MySQL Connector/J. Generally, you configure a connection pool in your application server configuration files, and access it via the Java Naming and Directory Interface (JNDI). The following code shows how you might use a connection pool from an application deployed in a J2EE application server: Example 23.11. Using a connection pool with a J2EE application server import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import javax.naming.InitialContext;
import javax.sql.DataSource;
public class MyServletJspOrEjb {
public void doSomething() throws Exception {
/*
* Create a JNDI Initial context to be able to
* lookup the DataSource
*
* In production-level code, this should be cached as
* an instance or static variable, as it can
* be quite expensive to create a JNDI context.
*
* Note: This code only works when you are using servlets
* or EJBs in a J2EE application server. If you are
* using connection pooling in standalone Java code, you
* will have to create/configure datasources using whatever
* mechanisms your particular connection pooling library
* provides.
*/
InitialContext ctx = new InitialContext();
/*
* Lookup the DataSource, which will be backed by a pool
* that the application server provides. DataSource instances
* are also a good candidate for caching as an instance
* variable, as JNDI lookups can be expensive as well.
*/
DataSource ds =
(DataSource)ctx.lookup("java:comp/env/jdbc/MySQLDB");
/*
* The following code is what would actually be in your
* Servlet, JSP or EJB 'service' method...where you need
* to work with a JDBC connection.
*/
Connection conn = null;
Statement stmt = null;
try {
conn = ds.getConnection();
/*
* Now, use normal JDBC programming to work with
* MySQL, making sure to close each resource when you're
* finished with it, which allows the connection pool
* resources to be recovered as quickly as possible
*/
stmt = conn.createStatement();
stmt.execute("SOME SQL QUERY");
stmt.close();
stmt = null;
conn.close();
conn = null;
} finally {
/*
* close any jdbc instances here that weren't
* explicitly closed during normal code path, so
* that we don't 'leak' resources...
*/
if (stmt != null) {
try {
stmt.close();
} catch (sqlexception sqlex) {
// ignore -- as we can't do anything about it here
}
stmt = null;
}
if (conn != null) {
try {
conn.close();
} catch (sqlexception sqlex) {
// ignore -- as we can't do anything about it here
}
conn = null;
}
}
}
}As shown in the example above, after obtaining the JNDI InitialContext, and looking up the DataSource, the rest of the code should look familiar to anyone who has done JDBC programming in the past. The most important thing to remember when using connection pooling is to make sure that no matter what happens in your code (exceptions, flow-of-control, and so forth), connections, and anything created by them (such as statements or result sets) are closed, so that they may be re-used, otherwise they will be stranded, which in the best case means that the MySQL server resources they represent (such as buffers, locks, or sockets) may be tied up for some time, or worst case, may be tied up forever. What's the Best Size for my Connection Pool? As with all other configuration rules-of-thumb, the answer is: it depends. Although the optimal size depends on anticipated load and average database transaction time, the optimum connection pool size is smaller than you might expect. If you take Sun's Java Petstore blueprint application for example, a connection pool of 15-20 connections can serve a relatively moderate load (600 concurrent users) using MySQL and Tomcat with response times that are acceptable. To correctly size a connection pool for your application, you should create load test scripts with tools such as Apache JMeter or The Grinder, and load test your application. An easy way to determine a starting point is to configure your connection pool's maximum number of connections to be unbounded, run a load test, and measure the largest amount of concurrently used connections. You can then work backward from there to determine what values of minimum and maximum pooled connections give the best performance for your particular application. The following instructions are based on the instructions for Tomcat-5.x, available at http://jakarta.apache.org/tomcat/tomcat-5.0-doc/jndi-datasource-examples-howto.html which is current at the time this document was written.
First, install the .jar file that comes with Connector/J in
Next, Configure the JNDI DataSource by adding a declaration
resource to
<Context ....>
...
<Resource name="jdbc/MySQLDB"
auth="Container"
type="javax.sql.DataSource"/>
<!-- The name you used above, must match _exactly_ here!
The connection pool will be bound into JNDI with the name
"java:/comp/env/jdbc/MySQLDB"
-->
<ResourceParams name="jdbc/MySQLDB">
<parameter>
<name>factory</name>
<value>org.apache.commons.dbcp.BasicDataSourceFactory</value>
</parameter>
<!-- Don't set this any higher than max_connections on your
MySQL server, usually this should be a 10 or a few 10's
of connections, not hundreds or thousands -->
<parameter>
<name>maxActive</name>
<value>10</value>
</parameter>
<!-- You don't want to many idle connections hanging around
if you can avoid it, only enough to soak up a spike in
the load -->
<parameter>
<name>maxIdle</name>
<value>5</value>
</parameter>
<!-- Don't use autoReconnect=true, it's going away eventually
and it's a crutch for older connection pools that couldn't
test connections. You need to decide whether your application
is supposed to deal with SQLExceptions (hint, it should), and
how much of a performance penalty you're willing to pay
to ensure 'freshness' of the connection -->
<parameter>
<name>validationQuery</name>
<value>SELECT 1</value>
</parameter>
<!-- The most conservative approach is to test connections
before they're given to your application. For most applications
this is okay, the query used above is very small and takes
no real server resources to process, other than the time used
to traverse the network.
If you have a high-load application you'll need to rely on
something else. -->
<parameter>
<name>testOnBorrow</name>
<value>true</value>
</parameter>
<!-- Otherwise, or in addition to testOnBorrow, you can test
while connections are sitting idle -->
<parameter>
<name>testWhileIdle</name>
<value>true</value>
</parameter>
<!-- You have to set this value, otherwise even though
you've asked connections to be tested while idle,
the idle evicter thread will never run -->
<parameter>
<name>timeBetweenEvictionRunsMillis</name>
<value>10000</value>
</parameter>
<!-- Don't allow connections to hang out idle too long,
never longer than what wait_timeout is set to on the
server...A few minutes or even fraction of a minute
is sometimes okay here, it depends on your application
and how much spikey load it will see -->
<parameter>
<name>minEvictableIdleTimeMillis</name>
<value>60000</value>
</parameter>
<!-- Username and password used when connecting to MySQL -->
<parameter>
<name>username</name>
<value>someuser</value>
</parameter>
<parameter>
<name>password</name>
<value>somepass</value>
</parameter>
<!-- Class name for the Connector/J driver -->
<parameter>
<name>driverClassName</name>
<value>com.mysql.jdbc.Driver</value>
</parameter>
<!-- The JDBC connection url for connecting to MySQL, notice
that if you want to pass any other MySQL-specific parameters
you should pass them here in the URL, setting them using the
parameter tags above will have no effect, you will also
need to use & to separate parameter values as the
ampersand is a reserved character in XML -->
<parameter>
<name>url</name>
<value>jdbc:mysql://localhost:3306/test</value>
</parameter>
</ResourceParams>
</Context>In general, you should follow the installation instructions that come with your version of Tomcat, as the way you configure datasources in Tomcat changes from time-to-time, and unfortunately if you use the wrong syntax in your XML file, you will most likely end up with an exception similar to the following: Error: java.sql.SQLException: Cannot load JDBC driver class 'null ' SQL state: null
These instructions cover JBoss-4.x. To make the JDBC driver
classes available to the application server, copy the .jar
file that comes with Connector/J to the
<datasources>
<local-tx-datasource>
<!-- This connection pool will be bound into JNDI with the name
"java:/MySQLDB" -->
<jndi-name>MySQLDB</jndi-name>
<connection-url>jdbc:mysql://localhost:3306/dbname</connection-url>
<driver-class>com.mysql.jdbc.Driver</driver-class>
<user-name>user</user-name>
<password>pass</password>
<min-pool-size>5</min-pool-size>
<!-- Don't set this any higher than max_connections on your
MySQL server, usually this should be a 10 or a few 10's
of connections, not hundreds or thousands -->
<max-pool-size>20</max-pool-size>
<!-- Don't allow connections to hang out idle too long,
never longer than what wait_timeout is set to on the
server...A few minutes is usually okay here,
it depends on your application
and how much spikey load it will see -->
<idle-timeout-minutes>5</idle-timeout-minutes>
<!-- If you're using Connector/J 3.1.8 or newer, you can use
our implementation of these to increase the robustness
of the connection pool. -->
<exception-sorter-class-name>
com.mysql.jdbc.integration.jboss.ExtendedMysqlExceptionSorter
</exception-sorter-class-name>
<valid-connection-checker-class-name>
com.mysql.jdbc.integration.jboss.MysqlValidConnectionChecker
</valid-connection-checker-class-name>
</local-tx-datasource>
</datasources> The Spring Framework is a Java-based application framework designed for assisting in application design by providing a way to configure components. The technique used by Spring is a well known design pattern called Dependency Injection (see Inversion of Control Containers and the Dependency Injection pattern). This article will focus on Java-oriented access to MySQL databases with Spring 2.0. For those wondering, there is a .NET port of Spring appropriately named Spring.NET. Spring is not only a system for configuring components, but also includes support for aspect oriented programming (AOP). This is one of the main benefits and the foundation for Spring's resource and transaction management. Spring also provides utilities for integrating resource management with JDBC and Hibernate. For the examples in this section the MySQL world sample database will be used. The first task is to setup a MySQL data source through Spring. Components within Spring use the "bean" terminology. For example, to configure a connection to a MySQL server supporting the world sample database you might use: <util:map id="dbProps">
<entry key="db.driver" value="com.mysql.jdbc.Driver"/>
<entry key="db.jdbcurl" value="jdbc:mysql://localhost/world"/>
<entry key="db.username" value="myuser"/>
<entry key="db.password" value="mypass"/>
</util:map>
In the above example we are assigning values to properties that will be used in the configuration. For the datasource configuration: <bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${db.driver}"/>
<property name="url" value="${db.jdbcurl}"/>
<property name="username" value="${db.username}"/>
<property name="password" value="${db.password}"/>
</bean>
The placeholders are used to provide values for properties of this bean. This means that you can specify all the properties of the configuration in one place instead of entering the values for each property on each bean. We do, however, need one more bean to pull this all together. The last bean is responsible for actually replacing the placeholders with the property values. <bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="properties" ref="dbProps"/>
</bean>
Now that we have our MySQL data source configured and ready to go, we write some Java code to access it. The example below will retrieve three random cities and their corresponding country using the data source we configured with Spring. // Create a new application context. this processes the Spring config
ApplicationContext ctx =
new ClassPathXmlApplicationContext("ex1appContext.xml");
// Retrieve the data source from the application context
DataSource ds = (DataSource) ctx.getBean("dataSource");
// Open a database connection using Spring's DataSourceUtils
Connection c = DataSourceUtils.getConnection(ds);
try {
// retrieve a list of three random cities
PreparedStatement ps = c.prepareStatement(
"select City.Name as 'City', Country.Name as 'Country' " +
"from City inner join Country on City.CountryCode = Country.Code " +
"order by rand() limit 3");
ResultSet rs = ps.executeQuery();
while(rs.next()) {
String city = rs.getString("City");
String country = rs.getString("Country");
System.out.printf("The city %s is in %s%n", city, country);
}
} catch (SQLException ex) {
// something has failed and we print a stack trace to analyse the error
ex.printStackTrace();
// ignore failure closing connection
try { c.close(); } catch (SQLException e) { }
} finally {
// properly release our connection
DataSourceUtils.releaseConnection(c, ds);
}This is very similar to normal JDBC access to MySQL with the main difference being that we are using DataSourceUtils instead of the DriverManager to create the connection. While it may seem like a small difference, the implications are somewhat far reaching. Spring manages this resource in a way similar to a container managed data source in a J2EE application server. When a connection is opened, it can be subsequently accessed in other parts of the code if it is synchronized with a transaction. This makes it possible to treat different parts of your application as transactional instead of passing around a database connection.
Spring makes extensive use of the Template method design
pattern (see
Template
Method Pattern). Our immediate focus will be on the
The next example shows how to use
public class Ex2JdbcDao {
/**
* Data source reference which will be provided by Spring.
*/
private DataSource dataSource;
/**
* Our query to find a random city given a country code. Notice
* the ":country" parameter towards the end. This is called a
* named parameter.
*/
private String queryString = "select Name from City " +
"where CountryCode = :country order by rand() limit 1";
/**
* Retrieve a random city using Spring JDBC access classes.
*/
public String getRandomCityByCountryCode(String cntryCode) {
// A template that allows using queries with named parameters
NamedParameterJdbcTemplate template =
new NamedParameterJdbcTemplate(dataSource);
// A java.util.Map is used to provide values for the parameters
Map params = new HashMap();
params.put("country", cntryCode);
// We query for an Object and specify what class we are expecting
return (String)template.queryForObject(queryString, params, String.class);
}
/**
* A JavaBean setter-style method to allow Spring to inject the data source.
* @param dataSource
*/
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
}
The focus in the above code is on the
To access this code, you need to configure it with Spring by providing a reference to the data source. <bean id="dao" class="code.Ex2JdbcDao">
<property name="dataSource" ref="dataSource"/>
</bean>
At this point, we can just grab a reference to the DAO from
Spring and call
// Create the application context
ApplicationContext ctx =
new ClassPathXmlApplicationContext("ex2appContext.xml");
// Obtain a reference to our DAO
Ex2JdbcDao dao = (Ex2JdbcDao) ctx.getBean("dao");
String countryCode = "USA";
// Find a few random cities in the US
for(int i = 0; i < 4; ++i)
System.out.printf("A random city in %s is %s%n", countryCode,
dao.getRandomCityByCountryCode(countryCode));
This example shows how to use Spring's JDBC classes to
completely abstract away the use of traditional JDBC classes
including You might be wondering how we can add transactions into our code if we don't deal directly with the JDBC classes. Spring provides a transaction management package that not only replaces JDBC transaction management, but also allows declarative transaction management (configuration instead of code). In order to use transactional database access, we will need to change the storage engine of the tables in the world database. The downloaded script explicitly creates MyISAM tables which do not support transactional semantics. The InnoDB storage engine does support transactions and this is what we will be using. We can change the storage engine with the following statements. ALTER TABLE City ENGINE=InnoDB; ALTER TABLE Country ENGINE=InnoDB; ALTER TABLE CountryLanguage ENGINE=InnoDB; A good programming practice emphasized by Spring is separating interfaces and implementations. What this means is that we can create a Java interface and only use the operations on this interface without any internal knowledge of what the actual implementation is. We will let Spring manage the implementation and with this it will manage the transactions for our implementation. First you create a simple interface: public interface Ex3Dao {
Integer createCity(String name, String countryCode,
String district, Integer population);
}
This interface contains one method that will create a new city record in the database and return the id of the new record. Next you need to create an implementation of this interface. public class Ex3DaoImpl implements Ex3Dao {
protected DataSource dataSource;
protected SqlUpdate updateQuery;
protected SqlFunction idQuery;
public Integer createCity(String name, String countryCode,
String district, Integer population) {
updateQuery.update(new Object[] { name, countryCode,
district, population });
return getLastId();
}
protected Integer getLastId() {
return idQuery.run();
}
}
You can see that we only operate on abstract query objects here and don't deal directly with the JDBC API. Also, this is the complete implementation. All of our transaction management will be dealt with in the configuration. To get the configuration started, we need to create the DAO. <bean id="dao" class="code.Ex3DaoImpl">
<property name="dataSource" ref="dataSource"/>
<property name="updateQuery">...</property>
<property name="idQuery">...</property>
</bean>
Now you need to setup the transaction configuration. The
first thing you must do is create transaction manager to
manage the data source and a specification of what
transaction properties are required for for the
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*"/>
</tx:attributes>
</tx:advice>
The preceding code creates a transaction manager that
handles transactions for the data source provided to it. The
<aop:config>
<aop:pointcut id="daoMethods"
expression="execution(* code.Ex3Dao.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="daoMethods"/>
</aop:config>
This basically says that all methods called on the
Ex3Dao dao = (Ex3Dao) ctx.getBean("dao");
Integer id = dao.createCity(name, countryCode, district, pop);
We can verify from this that there is no transaction management happening in our Java code and it's all configured with Spring. This is a very powerful notion and regarded as one of the most beneficial features of Spring.
In many sitations, such as web applications, there will be a
large number of small database transactions. When this is
the case, it usually makes sense to create a pool of
database connections available for web requests as needed.
Although MySQL does not spawn an extra process when a
connection is made, there is still a small amount of
overhead to create and setup the connection. Pooling of
connections also alleviates problems such as collecting
large amounts of sockets in the
Setting up pooling of MySQL connections with Spring is as
simple as changing the data source configuration in the
application context. There are a number of configurations
that we can use. The first example is based on the
Jakarta
Commons DBCP library. The example below replaces the
source configuration that was based on
<bean id="dataSource" destroy-method="close"
class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${db.driver}"/>
<property name="url" value="${db.jdbcurl}"/>
<property name="username" value="${db.username}"/>
<property name="password" value="${db.password}"/>
<property name="initialSize" value="3"/>
</bean>
The configuration of the two solutions is very similar. The
difference is that DBCP will pool connections to the
database instead of creating a new connection every time one
is requested. We have also set a parameter here called
Another way to configure connection pooling is to configure
a data source in our J2EE application server. Using JBoss as
an example, you can set up the MySQL connection pool by
creating a file called
<jee:jndi-lookup id="dataSource" jndi-name="java:MySQL_DS"/> There are a few issues that seem to be commonly encountered often by users of MySQL Connector/J. This section deals with their symptoms, and their resolutions. Questions
Questions and Answers 24.4.5.3.1: When I try to connect to the database with MySQL Connector/J, I get the following exception: SQLException: Server configuration denies access to data source SQLState: 08001 VendorError: 0 What's going on? I can connect just fine with the MySQL command-line client. MySQL Connector/J must use TCP/IP sockets to connect to MySQL, as Java does not support Unix Domain Sockets. Therefore, when MySQL Connector/J connects to MySQL, the security manager in MySQL server will use its grant tables to determine whether the connection should be allowed.
You must add the necessary security credentials to the
MySQL server for this to happen, using the
Note
Testing your connectivity with the
mysql command-line client will not
work unless you add the WarningChanging privileges and permissions improperly in MySQL can potentially cause your server installation to not have optimal security properties. 24.4.5.3.2: My application throws an SQLException 'No Suitable Driver'. Why is this happening? There are three possible causes for this error:
24.4.5.3.3: I'm trying to use MySQL Connector/J in an applet or application and I get an exception similar to: SQLException: Cannot connect to MySQL server on host:3306. Is there a MySQL server running on the machine/port you are trying to connect to? (java.security.AccessControlException) SQLState: 08S01 VendorError: 0 Either you're running an Applet, your MySQL server has been installed with the "--skip-networking" option set, or your MySQL server has a firewall sitting in front of it. Applets can only make network connections back to the machine that runs the web server that served the .class files for the applet. This means that MySQL must run on the same machine (or you must have some sort of port re-direction) for this to work. This also means that you will not be able to test applets from your local file system, you must always deploy them to a web server. MySQL Connector/J can only communicate with MySQL using TCP/IP, as Java does not support Unix domain sockets. TCP/IP communication with MySQL might be affected if MySQL was started with the "--skip-networking" flag, or if it is firewalled.
If MySQL has been started with the "--skip-networking"
option set (the Debian Linux package of MySQL server does
this for example), you need to comment it out in the file
/etc/mysql/my.cnf or /etc/my.cnf. Of course your my.cnf
file might also exist in the 24.4.5.3.4: I have a servlet/application that works fine for a day, and then stops working overnight MySQL closes connections after 8 hours of inactivity. You either need to use a connection pool that handles stale connections or use the "autoReconnect" parameter (see Section 23.4.4.1, “Driver/Datasource Class Names, URL Syntax and Configuration Properties for Connector/J”).
Also, you should be catching SQLExceptions in your
application and dealing with them, rather than propagating
them all the way until your application exits, this is
just good programming practice. MySQL Connector/J will set
the SQLState (see
The following (simplistic) example shows what code that can handle these exceptions might look like:
Example 23.12. Example of transaction with retry logic public void doBusinessOp() throws SQLException {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
//
// How many times do you want to retry the transaction
// (or at least _getting_ a connection)?
//
int retryCount = 5;
boolean transactionCompleted = false;
do {
try {
conn = getConnection(); // assume getting this from a
// javax.sql.DataSource, or the
// java.sql.DriverManager
conn.setAutoCommit(false);
//
// Okay, at this point, the 'retry-ability' of the
// transaction really depends on your application logic,
// whether or not you're using autocommit (in this case
// not), and whether you're using transacational storage
// engines
//
// For this example, we'll assume that it's _not_ safe
// to retry the entire transaction, so we set retry
// count to 0 at this point
//
// If you were using exclusively transaction-safe tables,
// or your application could recover from a connection going
// bad in the middle of an operation, then you would not
// touch 'retryCount' here, and just let the loop repeat
// until retryCount == 0.
//
retryCount = 0;
stmt = conn.createStatement();
String query = "SELECT foo FROM bar ORDER BY baz";
rs = stmt.executeQuery(query);
while (rs.next()) {
}
rs.close();
rs = null;
stmt.close();
stmt = null;
conn.commit();
conn.close();
conn = null;
transactionCompleted = true;
} catch (SQLException sqlEx) {
//
// The two SQL states that are 'retry-able' are 08S01
// for a communications error, and 40001 for deadlock.
//
// Only retry if the error was due to a stale connection,
// communications problem or deadlock
//
String sqlState = sqlEx.getSQLState();
if ("08S01".equals(sqlState) || "40001".equals(sqlState)) {
retryCount--;
} else {
retryCount = 0;
}
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException sqlEx) {
// You'd probably want to log this . . .
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException sqlEx) {
// You'd probably want to log this as well . . .
}
}
if (conn != null) {
try {
//
// If we got here, and conn is not null, the
// transaction should be rolled back, as not
// all work has been done
try {
conn.rollback();
} finally {
conn.close();
}
} catch (SQLException sqlEx) {
//
// If we got an exception here, something
// pretty serious is going on, so we better
// pass it up the stack, rather than just
// logging it. . .
throw sqlEx;
}
}
}
} while (!transactionCompleted && (retryCount > 0));
}
Note
Use of the 24.4.5.3.5: I'm trying to use JDBC-2.0 updatable result sets, and I get an exception saying my result set is not updatable. Because MySQL does not have row identifiers, MySQL Connector/J can only update result sets that have come from queries on tables that have at least one primary key, the query must select every primary key and the query can only span one table (that is, no joins). This is outlined in the JDBC specification.
Note that this issue only occurs when using updatable
result sets, and is caused because Connector/J is unable
to guarantee that it can identify the correct rows within
the result set to be updated without having a unique
reference to each row. There is no requirement to have a
unique field on a table if you are using
24.4.5.3.6: I cannot connect to the MySQL server using Connector/J, and I'm sure the connection paramters are correct.
Make sure that the 24.4.5.3.7: I am trying to connect to my MySQL server within my application, but I get the following error and stack trace: java.net.SocketException MESSAGE: Software caused connection abort: recv failed STACKTRACE: java.net.SocketException: Software caused connection abort: recv failed at java.net.SocketInputStream.socketRead0(Native Method) at java.net.SocketInputStream.read(Unknown Source) at com.mysql.jdbc.MysqlIO.readFully(MysqlIO.java:1392) at com.mysql.jdbc.MysqlIO.readPacket(MysqlIO.java:1414) at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:625) at com.mysql.jdbc.Connection.createNewIO(Connection.java:1926) at com.mysql.jdbc.Connection.<init>(Connection.java:452) at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:411) The error probably indicates that you are using a older version of the Connector/J JDBC driver (2.0.14 or 3.0.x) and you are trying to connect to a MySQL server with version 4.1x or newer. The older drivers are not compatible with 4.1 or newer of MySQL as they do not support the newer authentication mechanisms.
It is likely that the older version of the Connector/J
driver exists within your application directory or your
24.4.5.3.8: My application is deployed through JBoss and I am using transactions to handle the statements on the MySQL database. Under heavy loads I am getting a error and stack trace, but these only occur after a fixed period of heavy activity. This is a JBoss, not Connector/J, issue and is connected to the use of transactions. Under heavy loads the time taken for transactions to complete can increase, and the error is caused because you have exceeded the predefined timeout.
You can increase the timeout value by setting the
MySQL AB provides assistance to the user community by means of its mailing lists. For Connector/J related issues, you can get help from experienced users by using the MySQL and Java mailing list. Archives and subscription information is available online at http://lists.mysql.com/java. For information about subscribing to MySQL mailing lists or to browse list archives, visit http://lists.mysql.com/. See Section 1.7.1, “MySQL Mailing Lists”. Community support from experienced users is also available through the JDBC Forum. You may also find help from other users in the other MySQL Forums, located at http://forums.mysql.com. See Section 1.7.2, “MySQL Community Support at the MySQL Forums”. The normal place to report bugs is http://bugs.mysql.com/, which is the address for our bugs database. This database is public, and can be browsed and searched by anyone. If you log in to the system, you will also be able to enter new reports. If you have found a sensitive security bug in MySQL, you can send email to security_at_mysql.com. Writing a good bug report takes patience, but doing it right the first time saves time both for us and for yourself. A good bug report, containing a full test case for the bug, makes it very likely that we will fix the bug in the next release. This section will help you write your report correctly so that you don't waste your time doing things that may not help us much or at all. If you have a repeatable bug report, please report it to the bugs database at http://bugs.mysql.com/. Any bug that we are able to repeat has a high chance of being fixed in the next MySQL release. To report other problems, you can use one of the MySQL mailing lists. Remember that it is possible for us to respond to a message containing too much information, but not to one containing too little. People often omit facts because they think they know the cause of a problem and assume that some details don't matter. A good principle is this: If you are in doubt about stating something, state it. It is faster and less troublesome to write a couple more lines in your report than to wait longer for the answer if we must ask you to provide information that was missing from the initial report. The most common errors made in bug reports are (a) not including the version number of Connector/J or MySQL used, and (b) not fully describing the platform on which Connector/J is installed (including the JVM version, and the platform type and version number that MySQL itself is installed on). This is highly relevant information, and in 99 cases out of 100, the bug report is useless without it. Very often we get questions like, “Why doesn't this work for me?” Then we find that the feature requested wasn't implemented in that MySQL version, or that a bug described in a report has already been fixed in newer MySQL versions. Sometimes the error is platform-dependent; in such cases, it is next to impossible for us to fix anything without knowing the operating system and the version number of the platform. If at all possible, you should create a repeatable, stanalone testcase that doesn't involve any third-party classes.
To streamline this process, we ship a base class for testcases
with Connector/J, named
'
In the
In the
In the
In any of the above three methods, you should use one of the
variants of the
If you need to use a JDBC URL that is different from
'jdbc:mysql:///test', override the method
Use the
Finally, create a public static void main(String[] args) throws Exception {
new MyBugReport().run();
}Once you have finished your testcase, and have verified that it demonstrates the bug you are reporting, upload it with your bug report to http://bugs.mysql.com/. The Connector/J Change History (Changelog) is located with the main Changelog for MySQL. See Section E.6, “MySQL Connector/J Change History”.
MySQL Connector/MXJ is a solution for deploying the MySQL database
engine ( MySQL Connector/MXJ is a Java Utility package for deploying and managing a MySQL database. Deploying and using MySQL can be as easy as adding an additional parameter to the JDBC connection url, which will result in the database being started when the first connection is made. This makes it easy for Java developers to deploy applications which require a database by reducing installation barriers for their end-users. MySQL Connector/MXJ makes the MySQL database appear to be a java-based component. It does this by determining what platform the system is running on, selecting the appropriate binary, and launching the executable. It will also optionally deploy an initial database, with any specified parameters. Included are instructions for use with a JDBC driver and deploying as a JMX MBean to JBoss. You can download sources and binaries from: http://dev.mysql.com/downloads/connector/mxj/ This a beta release and feedback is welcome and encouraged. Please send questions or comments to the MySQL and Java mailing list. Connector/MX
A summary of the different MySQL versions supplied with each Connector/MXJ release are shown in the table.
This guide provides information on the Connector/MXJ 5.x release. For information on using the older releases, please see the documentation included with the appropriate distribution.
Connector/MXJ consists of a Java class, a copy of the
![]()
It is important to note that Connector/MXJ is not an embedded
version of MySQL, or a version of MySQL written as part of a
Java class. Connector/MXJ works through the use of an embedded,
compiled binary of It is the Connector/MXJ wrapper, support classes and tools, that enable Connector/MXJ to appear as a MySQL instance.
When Connector/MXJ is initialized, the corresponding
Because Connector/MXJ works in combination with Connector/J, you can access and integrate with the MySQL instance through a JDBC connection. When you have finished with the server, the instance is terminated, and, by default, any data created during the session is retained within the temporary directory created when the instance was started.
Connector/MXJ and the embedded Connector/MXJ does not have a installation application or process, but there are some steps you can follow to make the installation and deployment of Connector/MXJ easier. Before you start, there are some baseline requirements for
Depending on your target installation/deployment environment you may also require:
Connector/MXJ is compatible with any platform supporting Java
and MySQL. By default, Connector/MXJ incorporates the
For more information on packaging your own Connector/MXJ with the platforms you require, see Section 23.5.5.1, “Creating your own Connector/MXJ Package” Because there is no formal installation process, the method, installation directory, and access methods you use for Connector/MXJ are entirely up to your individual requirements.
To perform a basic installation, choose a target directory for
the files included in the Connector/MXJ package. On Unix/Linux
systems you may opt to use a directory such as
To install the files, for a Connector/MXJ 5.0.4 installation:
For Connector/MXJ 5.0.4 and later you need the following JAR
files in your
For Connector/MXJ 5.0.3 and earlier, you need the following JAR files:
Once you have extracted the Connector/MXJ and Connector/J
components you can run one of the sample applications that
initiates a MySQL instance. You can test the installation by
running the java ConnectorMXJUrlTestExample jdbc:mysql:mxj://localhost:3336/test?server.basedir=/var/tmp/test-mxj [MysqldResource] launching mysqld (getOptions) [/var/tmp/test-mxj/bin/mysqld][--no-defaults] » [--pid-file=/var/tmp/test-mxj/data/MysqldResource.pid] » [--socket=mysql.sock][--datadir=/var/tmp/test-mxj/data] » [--port=3336][--basedir=/var/tmp/test-mxj] [MysqldResource] launching mysqld (driver_launched_mysqld_1) InnoDB: The first specified data file ./ibdata1 did not exist: InnoDB: a new database to be created! 060726 15:40:42 InnoDB: Setting file ./ibdata1 size to 10 MB InnoDB: Database physically writes the file full: wait... 060726 15:40:43 InnoDB: Log file ./ib_logfile0 did not exist: new to be created InnoDB: Setting log file ./ib_logfile0 size to 5 MB InnoDB: Database physically writes the file full: wait... 060726 15:40:43 InnoDB: Log file ./ib_logfile1 did not exist: new to be created InnoDB: Setting log file ./ib_logfile1 size to 5 MB InnoDB: Database physically writes the file full: wait... InnoDB: Doublewrite buffer not found: creating new InnoDB: Doublewrite buffer created InnoDB: Creating foreign key constraint system tables InnoDB: Foreign key constraint system tables created 060726 15:40:44 InnoDB: Started; log sequence number 0 0 060726 15:40:44 [Note] /var/tmp/test-mxj/bin/mysqld: ready for connections. Version: '5.0.22-max' socket: 'mysql.sock' port: 3336 MySQL Community Edition - Experimental (GPL) [MysqldResource] mysqld running as process: 1210 ------------------------ 5.0.22-max ------------------------ [MysqldResource] stopping mysqld (process: 1210) 060726 15:40:44 [Note] /var/tmp/test-mxj/bin/mysqld: Normal shutdown 060726 15:40:45 InnoDB: Starting shutdown... 060726 15:40:48 InnoDB: Shutdown completed; log sequence number 0 43655 060726 15:40:48 [Note] /var/tmp/test-mxj/bin/mysqld: Shutdown complete [MysqldResource] clearing options [MysqldResource] shutdown complete The above output shows an instance of MySQL starting, the necessary files being created (log files, InnoDB data files) and the MySQL database entering the running state. The instance is then shutdown by Connector/MXJ before the example terminates.
Connector/MXJ and Connector/J work together to enable you to
launch an instance of the
For more details, see Section 23.5.3, “Connector/MXJ Configuration”. For deployment within a JBoss environment, you must configure the JBoss environment to use the Connector/MXJ component within the JDBC parameters:
You may wish to create a separate users and database table spaces for each application, rather than using "root and test".
We highly suggest having a routine backup procedure for backing
up the database files in the The best way to ensure that your platform is supported is to run the JUnit tests. These will test the Connector/MXJ classes and the associated components.
The first thing to do is make sure that the components will
work on the platform. The
Requirements:
If building from source, All of the requirements from above, plus:
A feature of the MySQL Connector/J JDBC driver is the ability to specify a connection to an embedded Connector/MXJ instance through the use of the mxj keyword in the JDBC connection string. In the following example, we have a program which creates a connection, executes a query, and prints the result to the System.out. The MySQL database will be deployed and started as part of the connection process, and shutdown as part of the finally block.
You can find this file in the Connector/MXJ package as
import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import com.mysql.management.driverlaunched.ServerLauncherSocketFactory;
public class ConnectorMXJUrlTestExample {
public static String DRIVER = "com.mysql.jdbc.Driver";
public static String JAVA_IO_TMPDIR = "java.io.tmpdir";
public static void main(String[] args) throws Exception {
File ourAppDir = new File(System.getProperty(JAVA_IO_TMPDIR));
File databaseDir = new File(ourAppDir, "test-mxj");
int port = 3336;
String url = "jdbc:mysql:mxj://localhost:" + port + "/test" + "?"
+ "server.basedir=" + databaseDir;
System.out.println(url);
String userName = "root";
String password = "";
Class.forName(DRIVER);
Connection conn = null;
try {
conn = DriverManager.getConnection(url, userName, password);
printQueryResults(conn, "SELECT VERSION()");
} finally {
try {
if (conn != null)
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
ServerLauncherSocketFactory.shutdown(databaseDir, null);
}
}
public static void printQueryResults(Connection conn, String SQLquery)
throws Exception {
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(SQLquery);
int columns = rs.getMetaData().getColumnCount();
System.out.println("------------------------");
System.out.println();
while (rs.next()) {
for (int i = 1; i <= columns; i++) {
System.out.println(rs.getString(i));
}
System.out.println();
}
rs.close();
stmt.close();
System.out.println("------------------------");
System.out.flush();
Thread.sleep(100); // wait for System.out to finish flush
}
}To run the above program, be sure to have connector-mxj.jar and Connector/J in the CLASSPATH. Then type: java ConnectorMXJTestExample If you have a java application and wish to “embed” a MySQL database, make use of the com.mysql.management.MysqldResource class directly. This class may be instantiated with the default (no argument) constructor, or by passing in a java.io.File object representing the directory you wish the server to be "unzipped" into. It may also be instantiated with printstreams for "stdout" and "stderr" for logging. Once instantiated, a java.util.Map, the object will be able to provide a java.util.Map of server options appropriate for the platform and version of MySQL which you will be using. The MysqldResource enables you to "start" MySQL with a java.util.Map of server options which you provide, as well as "shutdown" the database. The following example shows a simplistic way to embed MySQL in an application using plain java objects.
You can find this file in the Connector/MXJ package as
import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;
import com.mysql.management.MysqldResource;
public class ConnectorMXJObjectTestExample {
public static String DRIVER = "com.mysql.jdbc.Driver";
public static String JAVA_IO_TMPDIR = "java.io.tmpdir";
public static void main(String[] args) throws Exception {
File ourAppDir = new File(System.getProperty(JAVA_IO_TMPDIR));
File databaseDir = new File(ourAppDir, "mysql-mxj");
int port = 3336;
MysqldResource mysqldResource = startDatabase(databaseDir, port);
String userName = "root";
String password = "";
Class.forName(DRIVER);
Connection conn = null;
try {
String url = "jdbc:mysql://localhost:" + port + "/test";
conn = DriverManager.getConnection(url, userName, password);
printQueryResults(conn, "SELECT VERSION()");
} finally {
try {
if (conn != null) {
conn.close();
}
} catch (Exception e) {
e.printStackTrace();
}
try {
mysqldResource.shutdown();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static MysqldResource startDatabase(File databaseDir, int port) {
MysqldResource mysqldResource = new MysqldResource(databaseDir);
Map database_options = new HashMap();
database_options.put("port", Integer.toString(port));
mysqldResource.start("test-mysqld-thread", database_options);
if (!mysqldResource.isRunning()) {
throw new RuntimeException("MySQL did not start.");
}
System.out.println("MySQL is running.");
return mysqldResource;
}
public static void printQueryResults(Connection conn, String SQLquery)
throws Exception {
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(SQLquery);
int columns = rs.getMetaData().getColumnCount();
System.out.println("------------------------");
System.out.println();
while (rs.next()) {
for (int i = 1; i <= columns; i++) {
System.out.println(rs.getString(i));
}
System.out.println();
}
rs.close();
stmt.close();
System.out.println("------------------------");
System.out.flush();
Thread.sleep(100); // wait for System.out to finish flush
}
}
Of course there are many options we may wish to set for a MySQL database. These options may be specified as part of the JDBC connection string simply by prefixing each server option with ''server.''. In the following example we set two driver parameters and two server parameters: String url = "jdbc:mysql://" + hostColonPort + "/"
+ "?"
+ "cacheServerConfiguration=true"
+ "&"
+ "useLocalSessionState=true"
+ "&"
+ "server.basedir=/opt/myapp/db"
+ "&"
+ "server.datadir=/mnt/bigdisk/myapp/data";
The
MysqldResource API includes the following methods:
This section contains notes and tips on using the Connector/MXJ component within your applications.
If you want to create a custom Connector/MXJ package that
includes a specific
First, you should create a new directory into which you can
extract the current shell> mkdir custom-mxj shell> cd custom-mxj shell> jar -xf connector-mxj.jar shell> ls 5-0-22/ ConnectorMXJObjectTestExample.class ConnectorMXJUrlTestExample.class META-INF/ TestDb.class com/ kill.exe
If you are using Connector/MXJ v5.0.4 or later, you should
unpack the shell> mkdir custom-mxj shell> cd custom-mxj shell> jar -xf connector-mxj-db-files.jar shell> ls 5-0-27/ META-INF/ connector-mxj.properties
The MySQL version directory,
Within the version specific directory are the platform specific
directories, and archives of the shell>> ls Linux-i386/ META-INF/ Mac_OS_X-ppc/ SunOS-sparc/ Win-x86/ com/ data_dir.jar share_dir.jar win_share_dir.jar
Platform specific directories are listed by their OS and
platform - for example the
To add a platform specific
On Unix systems, you can determine the platform using
shell> uname -p i386
Now you need to download or compile
Create a file called mysql-5.0.22-osx10.3-i386/bin/mysqld
You can now recreate the shell> cd custom-mxj shell> jar -cf ../connector-mxj.jar *
For Connector/MXJ v5.0.4 and later, you should repackage to the
shell> cd custom-mxj shell> jar -cf ../connector-mxj-db-files.jar * You should test this package using the steps outlined in Section 23.5.2.3, “Connector/MXJ Quick Start Guide”. Note
Because the
To include a pre-configured/populated database within your
Connector/MXJ JAR file you must create a custom
Note that if you are create databases using the InnoDB engine,
you must include the As a JMX MBean, MySQL Connector/MXJ requires a JMX v1.2 compliant MBean container, such as JBoss version 4. The MBean will uses the standard JMX management APIs to present (and allow the setting of) parameters which are appropriate for that platform. If you are not using the SUN Reference implementation of the JMX libraries, you should skip this section. Or, if you are deploying to JBoss, you also may wish to skip to the next section.
We want to see the MysqldDynamicMBean in action inside of a JMX
agent. In the
When this very simple agent is started, it will allow a MySQL database to be started and stopped with a web browser.
Once there is confidence that the MBean will function on the platform, deploying the MBean inside of a standard JMX Agent is the next step. Included are instructions for deploying to JBoss.
As of 1.0.6-beta version is the ability to have the MBean start the MySQL database upon start up. Also, we've taken advantage of the JBoss life-cycle extension methods so that the database will gracefully shut down when JBoss is shutdown. There are a wide variety of options available for obtaining support for using Connector/MXJ. You should contact the Connector/MXJ community for help before reporting a potential bug or problem. See Section 23.5.6.1, “Connector/MXJ Community Support”. MySQL AB provides assistance to the user community by means of a number of mailing lists and web based forums. You can find help and support through the MySQL and Java mailing list. For information about subscribing to MySQL mailing lists or to browse list archives, visit http://lists.mysql.com/. See Section 1.7.1, “MySQL Mailing Lists”. Community support from experienced users is also available through the MyODBC Forum. You may also find help from other users in the other MySQL Forums, located at http://forums.mysql.com. See Section 1.7.2, “MySQL Community Support at the MySQL Forums”. If you encounter difficulties or problems with Connector/MXJ, contact the Connector/MXJ community Section 23.5.6.1, “Connector/MXJ Community Support”. If reporting a problem, you should ideally include the following information with the email:
Remember that the more information you can supply to us, the more likely it is that we can fix the problem. If you believe the problem to be a bug, then you must report the bug through http://bugs.mysql.com/. The Connector/MXJ Change History (Changelog) is located with the main Changelog for MySQL. See Section E.7, “MySQL Connector/MXJ Change History”.
The PHP distribution and documentation are available from the PHP
Web site. MySQL provides the Secure FTP (sFTP) HostingAlden Hosting offers Secure FTP (sFTP) on our WEB 5 PLAN and our WEB 6 PLAN . At Alden Hosting we eat and breathe Secure FTP (sFTP)! We are the industry leader in providing affordable, quality and efficient Secure FTP (sFTP) hosting in the shared hosting marketplace. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
http://alden-servlet-Hosting.com
JSP at alden-servlet-Hosting.com
Servlets at alden-servlet-Hosting.com
Servlet at alden-servlet-Hosting.com
Tomcat at alden-servlet-Hosting.com
MySQL at alden-servlet-Hosting.com
Java at alden-servlet-Hosting.com
sFTP at alden-servlet-Hosting.com
http://alden-tomcat-Hosting.com
JSP at alden-tomcat-Hosting.com
Servlets at alden-tomcat-Hosting.com
Servlet at alden-tomcat-Hosting.com
Tomcat at alden-tomcat-Hosting.com
MySQL at alden-tomcat-Hosting.com
Java at alden-tomcat-Hosting.com
sFTP at alden-tomcat-Hosting.com
http://alden-sftp-Hosting.com
JSP at alden-sftp-Hosting.com
Servlets at alden-sftp-Hosting.com
Servlet at alden-sftp-Hosting.com
Tomcat at alden-sftp-Hosting.com
MySQL at alden-sftp-Hosting.com
Java at alden-sftp-Hosting.com
sFTP at alden-sftp-Hosting.com
http://alden-jsp-Hosting.com
JSP at alden-jsp-Hosting.com
Servlets at alden-jsp-Hosting.com
Servlet at alden-jsp-Hosting.com
Tomcat at alden-jsp-Hosting.com
MySQL at alden-jsp-Hosting.com
Java at alden-jsp-Hosting.com
sFTP at alden-jsp-Hosting.com
http://alden-java-Hosting.com
JSp at alden-java-Hosting.com
Servlets at alden-java-Hosting.com
Servlet at alden-java-Hosting.com
Tomcat at alden-java-Hosting.com
MySQL at alden-java-Hosting.com
Java at alden-java-Hosting.com
sFTP at alden-java-Hosting.com
JSP
Servlets
Tomcat
mysql
Java
JSP
Servlets
Tomcat
mysql
Java
JSP
Servlets
Tomcat
mysql
Java
JSP
Servlets
Tomcat
mysql
Java
JSP at JSP.aldenWEBhosting.com
Servlets at servlets.aldenWEBhosting.com
Tomcat at Tomcat.aldenWEBhosting.com
mysql at mysql.aldenWEBhosting.com
Java at Java.aldenWEBhosting.com
Web Hosts Portal
Web Links
Web Links JSP
Web Links servlet
Tomcat Docs
Web Links
Web Links JSP
Web Links servlet
Web Hosting
Tomcat Docs
JSP Solutions Web Links
JSP Solutions Web Hosting
Servlets Solutions Web Links
Servlets Solutions Web Hosting
Web Links
Web Links
.
.
.
.
.
.
.
.
.
.
jsp hosting
servlets hosting
web hosting
web sites designed
cheap web hosting
web site hosting
myspace web hosting