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.
1. C Connect to MySQL database
First create a new C project in VS, right-click the project name and select Properties.
Select platform selection
Select configuration manager
Select New
Select X64 from the drop-down menu. OK
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)
Select the connector-> General -> Additional library directory. Add C:\Program Files\MySQL\MySQL Server 5.5\lib; (select according to your own installation directory)
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)
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
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>
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!

MySQLdiffersfromotherSQLdialectsinsyntaxforLIMIT,auto-increment,stringcomparison,subqueries,andperformanceanalysis.1)MySQLusesLIMIT,whileSQLServerusesTOPandOracleusesROWNUM.2)MySQL'sAUTO_INCREMENTcontrastswithPostgreSQL'sSERIALandOracle'ssequenceandt

MySQL partitioning improves performance and simplifies maintenance. 1) Divide large tables into small pieces by specific criteria (such as date ranges), 2) physically divide data into independent files, 3) MySQL can focus on related partitions when querying, 4) Query optimizer can skip unrelated partitions, 5) Choosing the right partition strategy and maintaining it regularly is key.

How to grant and revoke permissions in MySQL? 1. Use the GRANT statement to grant permissions, such as GRANTALLPRIVILEGESONdatabase_name.TO'username'@'host'; 2. Use the REVOKE statement to revoke permissions, such as REVOKEALLPRIVILEGESONdatabase_name.FROM'username'@'host' to ensure timely communication of permission changes.

InnoDB is suitable for applications that require transaction support and high concurrency, while MyISAM is suitable for applications that require more reads and less writes. 1.InnoDB supports transaction and bank-level locks, suitable for e-commerce and banking systems. 2.MyISAM provides fast read and indexing, suitable for blogging and content management systems.

There are four main JOIN types in MySQL: INNERJOIN, LEFTJOIN, RIGHTJOIN and FULLOUTERJOIN. 1.INNERJOIN returns all rows in the two tables that meet the JOIN conditions. 2.LEFTJOIN returns all rows in the left table, even if there are no matching rows in the right table. 3. RIGHTJOIN is contrary to LEFTJOIN and returns all rows in the right table. 4.FULLOUTERJOIN returns all rows in the two tables that meet or do not meet JOIN conditions.

MySQLoffersvariousstorageengines,eachsuitedfordifferentusecases:1)InnoDBisidealforapplicationsneedingACIDcomplianceandhighconcurrency,supportingtransactionsandforeignkeys.2)MyISAMisbestforread-heavyworkloads,lackingtransactionsupport.3)Memoryengineis

Common security vulnerabilities in MySQL include SQL injection, weak passwords, improper permission configuration, and unupdated software. 1. SQL injection can be prevented by using preprocessing statements. 2. Weak passwords can be avoided by forcibly using strong password strategies. 3. Improper permission configuration can be resolved through regular review and adjustment of user permissions. 4. Unupdated software can be patched by regularly checking and updating the MySQL version.

Identifying slow queries in MySQL can be achieved by enabling slow query logs and setting thresholds. 1. Enable slow query logs and set thresholds. 2. View and analyze slow query log files, and use tools such as mysqldumpslow or pt-query-digest for in-depth analysis. 3. Optimizing slow queries can be achieved through index optimization, query rewriting and avoiding the use of SELECT*.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver CS6
Visual web development tools

SublimeText3 Chinese version
Chinese version, very easy to use

Notepad++7.3.1
Easy-to-use and free code editor

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.
