Now we are working on an interface to operate different databases through different connection strings. To useMySQLDatabase. This database has never been used before. There are many access and SQL server databases. Through some information on the Internet and self-exploration, it is roughly clearC ++Connect to mysql. You can achieve this in two ways.
The first method is to connect using ADO,
The second method is to use mysql's own api functions for connection.
The first method can achieve my current needs by connecting different strings to connect different databases. Currently, only mysql, sqlserver, oracle, and access are connected. For access, because the SQL statement used to create a table is not compatible with standard SQL statements, some processing is required. The second method can only be used for mysql database connections. However, you do not need to install the MyODBC server program in this method.
No matter which method is used, you must first install the Mysql database. For the installation method, see "mysql installation and some precautions ". It is best to install a Navicat for mysql to facilitate operations on the mysql database. The two methods are described as follows:
(1) connecting to the MySQL database through ado
1. to connect to the MySQL database through ado, first install the myodbc server program.
The MyODBC version must match the MySql version. Otherwise, the database cannot be connected. The versions I use are mysql-5.1.48-win32.msi and mysql-connector-odbc-5.1.5-win32.msi.
After installation, choose Start> Settings> Control Panel> Administrative Tools> data source (ODBC)> User DSN> Add> select MySQL ODBC 5.1 Driver. For example:
Double-click MySQL ODBC 5.1 Driver. After configuration, click Test to perform the Test (for example). If the connection is successful, the connection successful dialog box is displayed.
Data Source Name in: the content is the value corresponding to the DSN in the code.
For example, "DSN = MySqlODBC; server = localhost; database = test ".
2. After configuration, you can start encoding.
(1) first import the ADO database. # Import "c: \ program files \ common files \ system \ ado \ msado15.dll" no_namespace rename ("EOF", "adoEOF "). Msado15.dll is not necessarily in this directory in your environment. modify it as needed. Or copy the msado15.dll file to your project directory and directly include # import "msado15.dll" \ no_namespace \ rename ("EOF", "adoEOF.
(2) create a Connection object and connect to the database
- {
- Coinitialize (null );
- M_pconnection.createinstance (_ uuidof (connection ));
- Try
- {
- // Set the connection time
- M_pconnection-> connectiontimeout = 5;
- // Open the database connection
- Hresult hR = m_pconnection-> open ("DSN = mysqlodbc; server = localhost; database = test", "root", "root", admodeunknown );
- }
- Catch (_ com_error & E)
- {
- MessageBox (NULL, e. Description (), _ T (""), MB_ OK );
- Return FALSE;
- }
- Return TRUE;
- }
(3) Execute SQL statements
- BOOL CDBManagerSub: ExecuteSQL (_ bstr_t bstrSQL)
- {
- // _ Variant_t RecordsAffected;
- Try
- {
- // Whether the database has been connected
- If (m_pConnection = NULL)
- {
- // Reconnect to the database
- Open (m_dbType, m_strServer, m_strUserName, m_strPasswor, m_strDBName );
- }
- // Execute method of the Connection object :( _ bstr_t CommandText,
- // VARIANT * RecordsAffected, long Options)
- // CommandText is a command string, usually an SQL command.
- // The RecordsAffected parameter indicates the number of rows affected by the operation,
- // The Options parameter indicates the CommandText type: adCmdText-text command; adCmdTable-Table Name
- // Adw.proc-stored procedure; adCmdUnknown-Unknown
- _ RecordsetPtr hr = m_pConnection-> Execute (bstrSQL, NULL, ad1_text );
- Return true;
- }
- Catch (_ com_error e)
- {
- MessageBox (NULL, e. Description (), _ T (""), MB_ OK );
- Return false;
- }
- }
_ Bstr_t bstrSQL is the input SQL statement. If TRUE is returned, the execution is successful. If FLASH is returned, an error message is returned.
For example, the following SQL statement used to create a testTable table:
- char* pQuery = "create table if not exists testTable( ID VARCHAR(10), Name VARCHAR(255),Descs VARCHA(255),PRIMARY KEY (ID))";
- ExecuteSQL(pQuery);
3. Attach the MySQL database operation for your reference if you have not installed navicat for MySQL.
Open "start-> All Programs-> MySQL Server 5.0-> MySQL Command Line Client.exe". If no password is set, press enter and a message is displayed, indicating that the Server is successfully started.
- Mysql> show databases; // display all DATABASES. Be sure to press ";" and press Enter.
- Mysql> create database mydb; // CREATE a DATABASE
- Mydbmysql> USE mydb; // select the database you created
- Mydbmysql> show tables; // display tables in the database
- Mysql> Create Table mytable (username varchar (100), visitelist varchar (200), remark varchar (200), primary key (username); // create a table mytable: User Name; access list. The primary key is username.
- Mysql> describe mytable; // displays the table structure.
(2) connect through MySQL's own API functions
1. To Connect using APIs, You need to load the MySQL header file and Lib file.
Add \ MySQL Server 5.1 \ include to the additional include directory of VS2010. Find it in the directory where MySql is installed. Copy the libmysql. dll and libmysql. lib files to the created project directory. The header file contains the following content:
- // Header files and library files required by MySQL
- # Include "Winsock. H"
- # Include "mysql. H"
- # Pragma comment (Lib, "libmysql. lib ")
2. Encoding
(1) connect to the mysql database
The data source pointer MYSQL m_sqlCon is defined in the header file;
// Connect to the MySql database
- Try
- {
- Mysql_init (& m_sqlcon );
- // Localhost: the root account and password of the server. "test" indicates the database name. "3306" indicates the port number.
- If (! Mysql_real_connect (& m_sqlcon, "localhost", "root", "root", "test", 3306, null, 0 ))
- {
- Afxmessagebox (_ T ("database connection failed! "));
- Return false;
- }
- Return TRUE;
- }
- Catch (...)
- {
- Return FALSE;
- }
(2) shut down the database
- mysql_close(&m_sqlCon);
(3) create a table
- char* pQuery = "create table if not exists DS_Building( ID VARCHAR(10),Name VARCHAR(255),Descs VARCHAR(255),PRIMARY KEY (ID))"
- if(mysql_real_query(&m_sqlCon,pQuery,(UINT)strlen(pQuery))!=0)
- {
- const char* pCh = mysql_error(&m_sqlCon);
- return FALSE;
- }
Attached MySQL API:
- Mysql_affected_rows () returns the number of rows affected by the latest UPDATE, DELETE, or INSERT query.
- Mysql_close () closes a server connection.
- Mysql_connect () connects to a MySQL server. This function is not recommended; Use mysql_real_connect () instead.
- Mysql_change_user () changes the user and database on an open connection.
- Mysql_create_db () creates a database. This function is not recommended, but the SQL command CREATE DATABASE is used.
- Mysql_data_seek () searches for any row in a query result set.
- Mysql_debug () uses the given string for DBUG_PUSH.
- Mysql_drop_db () discards a database. This function is not recommended, but the SQL command DROP DATABASE is used.
- Mysql_dump_debug_info () allows the server to write debugging information to the log file.
- Mysql_eof () determines whether the last row of a result set has been read. This function is opposed; mysql_errno () or mysql_error () can be used on the contrary.
- Mysql_errno () returns the error number of the recently called MySQL function.
- Mysql_error () returns the error message of the recently called MySQL function.
- Use mysql_escape_string () to escape special characters from strings in SQL statements.
- Mysql_fetch_field () returns the type of the field in the next table.
- Mysql_fetch_field_direct () returns the type of a table field and a field number.
- Mysql_fetch_fields () returns an array of all field structures.
- Mysql_fetch_lengths () returns the length of all columns in the current row.
- Mysql_fetch_row () gets the next row from the result set.
- Mysql_field_seek () Place the column cursor on a specified column.
- Mysql_field_count () returns the number of result columns of the latest query.
- Mysql_field_tell () returns the cursor position for the last mysql_fetch_field () field.
- Mysql_free_result () releases the memory used by a result set.
- Mysql_get_client_info () returns the customer version information.
- Mysql_get_host_info () returns a string that describes the connection.
- Mysql_get_proto_info () returns the Protocol version used by the connection.
- Mysql_get_server_info () returns the server version number.
- Mysql_info () returns information about the recently executed query.
- Mysql_init () obtains or initializes a MYSQL structure.
- Mysql_insert_id () returns the ID generated by the previous query for the AUTO_INCREMENT column.
- Mysql_kill () kills a given thread.
- Mysql_list_dbs () returns the database name that matches a simple regular expression.
- Mysql_list_fields () returns the column name that matches a simple regular expression.
- Mysql_list_processes () returns a table of the current server thread.
- Mysql_list_tables () returns the table name that matches a simple regular expression.
- Mysql_num_fields () returns the number of duplicate columns in a result set.
- Mysql_num_rows () returns the number of rows in a result set.
- Mysql_options () sets the connection options for mysql_connect.
- Mysql_ping () checks whether the connection to the server is working and reconnects if necessary.
- Mysql_query () executes an SQL query specified as an empty string.
- Mysql_real_connect () connects to a MySQL server.
- Mysql_real_query () executes an SQL query specified as a string with a count.
- Mysql_reload () tells the server to reinstall the authorization table.
- Mysql_row_seek () searches for rows in the result set and uses the values returned from mysql_row_tell.
- Mysql_row_tell () returns the cursor position of the row.
- Mysql_select_db () connects to a database.
- Mysql_shutdown () disables the database server.
- Mysql_stat () returns the server status as a string.
- Mysql_store_result () retrieves a complete set of results for the customer.
- Mysql_thread_id () returns the ID of the current thread.
- Mysql_use_result () initializes the retrieval of a result set in one row and one row.
Through the introduction in this article, I hope you have some knowledge about the two methods for connecting C ++ to the mysql database for your reference.
Http://developer.51cto.com/art/201104/257338.htm