Home > Database > Mysql Tutorial > How to connect and use MySQL database in C++

How to connect and use MySQL database in C++

醉折花枝作酒筹
Release: 2021-07-02 09:28:29
forward
5934 people have browsed it

In C, you can also use the database. Today we will learn how to connect and use the MySQL database in C. Friends in need can refer to it.

How to connect and use MySQL database in C++

1. C Connect to MySQL database

First create a new C project in VS, right-click the project name and select Properties.

How to connect and use MySQL database in C++

Select platform selection

How to connect and use MySQL database in C++

Select configuration manager

How to connect and use MySQL database in C++

Select New

How to connect and use MySQL database in C++

Select X64 from the drop-down menu. OK

How to connect and use MySQL database in C++

Select C/C -> General- > Attach the include directory, add C:\Program Files\MySQL\MySQL Server 5.5\include (select according to your own installation directory)

How to connect and use MySQL database in C++

Select the connector-> General -> Additional library directory. Add C:\Program Files\MySQL\MySQL Server 5.5\lib; (select according to your own installation directory)

How to connect and use MySQL database in C++

Select connector-> Enter-> Additional dependencies item. Add C:\Program Files\MySQL\MySQL Server 5.5\lib\libmysql.lib; (select according to your own installation directory)

How to connect and use MySQL database in C++

Finally add the dynamic link library libmysql.dll Copy it to the X64 build directory of the project. The dynamic link library file is in the C:\Program Files\MySQL\MySQL Server 5.5\lib\ directory

How to connect and use MySQL database in C++

2. MySQL common API functions

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() Connect to a MySQL server. This function is deprecated; use mysql_real_connect() instead.

mysql_change_user() Changes the user and database on an open connection.

mysql_create_db() Create a database. This function is not recommended; use the SQL command CREATE DATABASE instead.

mysql_data_seek() Searches for an arbitrary row in a query result set.

mysql_debug() does a DBUG_PUSH with the given string.

mysql_drop_db() Drops a database. This function is not recommended; use the SQL command DROP DATABASE instead.

mysql_dump_debug_info() Let the server write debugging information to the log file.

mysql_eof() Determines whether the last row of a result set has been read. This feature is deprecated; mysql_errno() or mysql_error() can be used instead.

mysql_errno() Returns the error number of the most recently called MySQL function.

mysql_error() returns the error message of the most recently called MySQL function.

mysql_escape_string() Escape special characters used in strings in SQL statements.

mysql_fetch_field() returns the type of the next table field.

mysql_fetch_field_direct () Returns the type of a table field, giving 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 most recent query.

mysql_field_tell() Returns the position of the field cursor used for the last mysql_fetch_field().

mysql_free_result() releases the memory used by a result set.

mysql_get_client_info() returns client version information.

mysql_get_host_info() returns a string describing 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 most recently executed query.

mysql_init() Obtains or initializes a MYSQL structure.

mysql_insert_id() returns the ID generated by the previous query for an AUTO_INCREMENT column.

mysql_kill() Kills a given thread.

mysql_list_dbs() Returns the database name matching a simple regular expression.

mysql_list_fields() Returns column names that match a simple regular expression.

mysql_list_processes() returns a table for the current server thread.

mysql_list_tables() Returns table names matching a simple regular expression.

mysql_num_fields() Returns the number of 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() Execute a SQL query specified as a null-terminated string.

mysql_real_connect() Connect to a MySQL server.

mysql_real_query() Execute a SQL query specified as a string with count.

mysql_reload() tells the server to reload the authorization table.

mysql_row_seek() searches for a row in the result set, using the value returned from mysql_row_tell().

mysql_row_tell() returns the row cursor position.

mysql_select_db() Connect to a database.

mysql_shutdown() Shut down the database server.

mysql_stat() Returns the server status as a string.

mysql_store_result() retrieves a complete result set to the client.

mysql_thread_id() returns the ID of the current thread.

mysql_use_result() Initializes the retrieval of a row-by-row result set.

3. C Use MySQL database

Sample program, digest it yourself, if you don’t understand the included API, just Google

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<windows.h>
#include<winsock.h>
#include<mysql.h>


using namespace std;
#pragma comment(lib,"libmysql.lib")
#pragma comment(lib,"wsock32.lib")
MYSQL *mysql = new MYSQL; //mysql连接  
MYSQL_FIELD *fd;    //字段列数组  
char field[32][32];    //存字段名二维数组  
MYSQL_RES *res; //这个结构代表返回行的一个查询结果集  
MYSQL_ROW column; //一个行数据的类型安全(type-safe)的表示,表示数据行的列  
char query[150]; //查询语句  

bool ConnectDatabase();
bool QueryDatabase1();
//bool QueryDatabase2();
int main()
{
    ConnectDatabase();
    QueryDatabase1();
    //QueryDatabase2();
    system("pause");
    return 0;
}


bool ConnectDatabase()
{
    //初始化mysql  
    mysql_init(mysql);
    //返回false则连接失败,返回true则连接成功  
    if (!(mysql_real_connect(mysql, "localhost", "root", "123456", "company", 0, NULL, 0))) //中间分别是主机,用户名,密码,数据库名,端口号(可以写默认0或者3306等),可以先写成参数再传进去  
    {
        printf("Error connecting to database:%s\n", mysql_error(mysql));
        return false;
    }
    else
    {
        printf("Connected...\n");
        return true;
    }
    return true;
}

bool QueryDatabase1()
{
    sprintf_s(query, "select * from t_dept"); //执行查询语句,这里是查询所有,user是表名,不用加引号,用strcpy也可以  
    mysql_query(mysql, "set names gbk"); //设置编码格式(SET NAMES GBK也行),否则cmd下中文乱码  
    //返回0 查询成功,返回1查询失败  
    if (mysql_query(mysql, query))    //执行SQL语句
    {
        printf("Query failed (%s)\n", mysql_error(mysql));
        return false;
    }
    else
    {
        printf("query success\n");
    }
    //获取结果集  
    if (!(res = mysql_store_result(mysql)))   //获得sql语句结束后返回的结果集  
    {
        printf("Couldn't get result from %s\n", mysql_error(mysql));
        return false;
    }

    //打印数据行数  
    printf("number of dataline returned: %d\n", mysql_affected_rows(mysql));

    //获取字段的信息  
    char *str_field[32];  //定义一个字符串数组存储字段信息  
    for (int i = 0; iname;
    }
    for (int i = 0; i<p>Related learning recommendations: <a href="https://www.php.cn/course/list/51.html" target="_blank">mysql tutorial</a> (video)</p></mysql.h></winsock.h></windows.h></iostream>
Copy after login

The above is the detailed content of How to connect and use MySQL database in C++. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template