share it today . Vs2013mfc uses MySQL 's own API function to connect to the MySQL database, the database is installed here not to say much, Can find tutorials, I mainly record the c++mfc Connection database. It is necessary to note that the VS2013 I am using is a three-bit, so MYSQL must also use + bit, so that there will be no inexplicable marvelous mistake. Proceed to the next step:
One: Project configuration
1. Open the mysql installation path and locate the include folder and lib folder
2. Open Project –> Properties –>vc++ directory
:
add include and Lib to the Include directory and library directory, respectively .
3. Open Project –> Properties –> linker –> input –> Additional Dependencies
:
Add the Libmysql.lib , or you can add them manually in the CPP file .
4. finally , copy the Libmysql.dll dynamic library to the project file. Otherwise, the runtime will prompt for the missing library.
Two: Code editing
1. Connect to the database:
initializing the database
Mysql_init (&local_mysql);
set the database encoding format
Mysql_options (&local_mysql, Mysql_set_charset_name, "GBK");
connecting to a database
if (!mysql_real_connect (&local_mysql, "localhost", "root", "123456", Db_name, 9806, NULL, 0))
{
AfxMessageBox ("Connect to Database failed!");
return FALSE;
}
2. Execute SQL Statements
defines a character array that stores the SQL statement to execute
Char sql_select[100];
Put the SQL statement you want to execute into the array
sprintf (Sql_select, "select *from USERINFO WHERE user= '%s ';", USER);
EXECUTE Statement
if (mysql_query (&local_mysql, sql_select) = = 0)// Execute the query statement successfully!
{
Execute SQL statement succeeded
}
3. other
Check if the database is connected
if (mysql_ping (&local_mysql) = = 0)/
{
AfxMessageBox ("The database is connected! ")
}
Disconnecting database Connections
Mysql_close (&local_mysql);
get SQL execution Error results
Mysql_error (&local_mysql);// Get database error message
4. Get Data Set
To get a result set from the execution result
mysql_res* result = Mysql_store_result (&local_mysql);
Mysql_row ROW;
read the result line-wise until you finish reading
while (row = mysql_fetch_row (result))
{
working with row-wise results
M_data[i].push_back (M_row[0]);
M_data[i].push_back (m_row[1]);
M_data[i].push_back (m_row[2]);
M_data[i].push_back (M_row[3]);
M_data[i].push_back (M_row[4]);
M_data[i++].push_back (M_row[5]);
}
If you have any questions or need background server communication, please contact me qq:2769519484
C++mfc connect to MySQL database