Home Database Mysql Tutorial mysql的安装、C++访问mysql数据库、编码设置问题_MySQL

mysql的安装、C++访问mysql数据库、编码设置问题_MySQL

Jun 01, 2016 pm 01:08 PM

一.mysql的安装,这个相对简单,直接去官网下载mysql安装程序,就可以完成安装过程,网上有很多安装教程,这个没什么注意事项。

 

二、C++访问mysql,主要是用到mysql定义的头文件,内部定义了各种数据结构和函数,比如MYSQL,MYSQL_RES,MYSQL_ROW,mysql_real_connect等等一系列的结构和函数。这里要注意的就是将头文件及lib文件以及dll文件配置到当前开发环境来进行访问mysql数据库。

以最新的vs2013作为示例说一下配置过程。为了写的清晰点,在网上找了几张图来说明。

 

1.要指定mysql所用到的头文件,可以直接将mysql安装目录下的include文件下的头文件拷贝到vs安装目录的include目录下,但是一般我们都是为编译器指定一个额外的头文件目录即可。右键工程-> properties然后如下图,在这个附加包含目录(Additional Include Directory)添加上mysql的include文件,此文件在mysql安装目录下,例如本人的安装目录

C:\Program Files\MySQL\MySQL Server 5.1\include



 

2.指定mysql的库文件

在连接器的常规下面,附加库目录(Additional Liberay Directory)添加上mysql安装目录下的lib文件夹的路径,本人的安装目录:

C:\Program Files\MySQL\MySQL Server 5.5\lib

本文作者:csdn  iaccepted 凌风



 

3.添加额外依赖(AdditionalDependencies),如下图,指定libmysql.lib,其实就是在上面设置的库文件中指定用哪个lib文件而已。



 

ok,到这里环境就配置完成,接下来就可以进行连接mysql并进行数据库操作。

本文作者:csdn  iaccepted 凌风


 

在vs2013中新建一个工程,然后根据mysql的官方API就可以完成数据库操作。

如下:

[cpp] view plaincopyprint?在CODE上查看代码片派生到我的代码片

  1. #include "person.h"  
  2. #include   
  3. #include   
  4. #include   
  5. #include   
  6. #include   
  7.   
  8.   
  9. using namespace std;  
  10.   
  11. int main(){  
  12.     MYSQL *con;  
  13.     MYSQL_RES *results;  
  14.     MYSQL_ROW record;  
  15.   
  16.     char dbuser[30] = "root";  
  17.     char dbpasswd[30] = "123456";  
  18.     char dbhost[30] = "localhost";  
  19.     char dbname[30] = "person";  
  20.     char tname[30] = "person";  
  21.     char *query = nullptr;  
  22.   
  23.     con = mysql_init(nullptr);  
  24.   
  25.     if (!mysql_real_connect(con, dbhost, dbuser, dbpasswd, dbname, 3306, NULL, 0)){  
  26.         cerr "Failed to connect database" 
  27.         exit(2);  
  28.     }  
  29.   
  30.   
  31.     mysql_set_character_set(con, "gbk");  
  32.       
  33.     mysql_query(con, "insert into person(id, name) values('370983198811256977', '个')");  
  34.   
  35.     mysql_query(con, "select name,id from person where id = '370983198811256977'");  
  36.   
  37.     results = mysql_store_result(con);  
  38.   
  39.     cout 
  40.   
  41.     while ((record = mysql_fetch_row(results))){  
  42.         cout 
  43.     }  
  44.       
  45.     mysql_close(con);  
  46.     return 0;   
  47. }  
#include "person.h"
#include <Windows.h>
#include <iostream>
#include <string>
#include <mysql.h>
#include <winsock.h>


using namespace std;

int main(){
	MYSQL *con;
	MYSQL_RES *results;
	MYSQL_ROW record;

	char dbuser[30] = "root";
	char dbpasswd[30] = "123456";
	char dbhost[30] = "localhost";
	char dbname[30] = "person";
	char tname[30] = "person";
	char *query = nullptr;

	con = mysql_init(nullptr);

	if (!mysql_real_connect(con, dbhost, dbuser, dbpasswd, dbname, 3306, NULL, 0)){
		cerr << "Failed to connect database" << endl;
		exit(2);
	}


	mysql_set_character_set(con, "gbk");
	
	mysql_query(con, "insert into person(id, name) values('370983198811256977', '个')");

	mysql_query(con, "select name,id from person where id = '370983198811256977'");

	results = mysql_store_result(con);

	cout << mysql_num_fields(results) << endl;

	while ((record = mysql_fetch_row(results))){
		cout << record[0] << endl;
	}
	
	mysql_close(con);
	return 0; 
}
Copy after login

正常情况下编译并运行就可以了。

但是有的时候会提示

main.obj : error LNK2019: unresolved externalsymbol _mysql_num_fields@4 referenced in function _main

1>main.obj : error LNK2019: unresolved externalsymbol _mysql_set_character_set@8 referenced in function _main

1>main.obj : error LNK2019: unresolved externalsymbol _mysql_init@4 referenced in function _main

1>main.obj : error LNK2019: unresolved externalsymbol _mysql_real_connect@32 referenced in function _main

1>main.obj : error LNK2019: unresolved externalsymbol _mysql_query@8 referenced in function _main

1>main.obj : error LNK2019: unresolved externalsymbol _mysql_store_result@4 referenced in function _main

1>main.obj : error LNK2019: unresolved externalsymbol _mysql_fetch_row@4 referenced in function _main

1>main.obj : error LNK2019: unresolved external symbol_mysql_close@4 referenced in function _main

 

意思就是说这些符号都无法找到从而导致链接失败。

很明显编译是正常的只是链接失败,首先回去检查上面的三项设置是否对了,如果没有错误的话可能是与系统的版本有关,比如说你用的是64为的windows系统,但是建立工程建立的却是32位的工程。这是后同上面一样,工程(project)右键->选项(properties)-> 在属性页(property pages)的最上面 有个平台选择(platform)然后选择x64,这样再回来编译就ok了

本文作者:csdn  iaccepted 凌风

三、中文乱码问题

查看mysql的用户手册能发现,mysql进行字符编码转换的步骤很明确:

 

1. MySQL Server收到请求时将请求数据从character_set_client转换为character_set_connection;

2. 进行内部操作前将请求数据从character_set_connection转换为内部操作字符集,其确定方法如下:

• 使用每个数据字段的CHARACTER SET设定值;

• 若上述值不存在,则使用对应数据表的DEFAULT CHARACTER SET设定值(MySQL扩展,非SQL标准);

• 若上述值不存在,则使用对应数据库的DEFAULT CHARACTER SET设定值;

• 若上述值不存在,则使用character_set_server设定值。

3. 将操作结果从内部操作字符集转换为character_set_results。

 

一般情况下我们将mysql的默认编码设置为utf8格式,然后在在客户端进行操作,当有中文操作时,我们先更改客户端的编码比如改为gbk,然后进行插入读取,这时候mysql在接受到数据时发现是gbk编码的,如上会将gbk编码转换成character_set_server编码的数据进行存入,在这里也就是将gbk转换为utf8。读取的时候mysql会自动将读取的结果从内部字符集转换为character_set_results指定的编码,即从uft8转换为gbk从而不会产生编码问题。

以上转换为自动进行的过程,程序员要做的只是设置好内部编码格式以及客户端编码格式即可,这里的客户端是广义的,既可以指command lineclint 也可以只应用程序,说白了就是任何要访问mysql的东西统称为客户端,如上面例子中的代码,C++程序作为客户端时,因为要操作中文,所以首先使用

mysql_set_character_set(con,"gbk");

将客户端编码设置为gbk,这样存入的中文mysql会进行转换而成为utf8格式,读取的时候mysql又会从utf8格式转换成gbk返回给客户端。

 

查看以上各编码的命令

 

  1. mysql> SHOW VARIABLES LIKE 'character%'; 

就可以看到character_set_server、character_set_connection、character_set_results等的值。


 

 

主要是理解上述所说的mysql字符编码转换的步骤,这样就能控制不会出现乱码问题。

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1246
24
MySQL: Simple Concepts for Easy Learning MySQL: Simple Concepts for Easy Learning Apr 10, 2025 am 09:29 AM

MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.

MySQL's Role: Databases in Web Applications MySQL's Role: Databases in Web Applications Apr 17, 2025 am 12:23 AM

The main role of MySQL in web applications is to store and manage data. 1.MySQL efficiently processes user information, product catalogs, transaction records and other data. 2. Through SQL query, developers can extract information from the database to generate dynamic content. 3.MySQL works based on the client-server model to ensure acceptable query speed.

Explain the role of InnoDB redo logs and undo logs. Explain the role of InnoDB redo logs and undo logs. Apr 15, 2025 am 12:16 AM

InnoDB uses redologs and undologs to ensure data consistency and reliability. 1.redologs record data page modification to ensure crash recovery and transaction persistence. 2.undologs records the original data value and supports transaction rollback and MVCC.

MySQL: An Introduction to the World's Most Popular Database MySQL: An Introduction to the World's Most Popular Database Apr 12, 2025 am 12:18 AM

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

MySQL's Place: Databases and Programming MySQL's Place: Databases and Programming Apr 13, 2025 am 12:18 AM

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

Why Use MySQL? Benefits and Advantages Why Use MySQL? Benefits and Advantages Apr 12, 2025 am 12:17 AM

MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

MySQL vs. Other Programming Languages: A Comparison MySQL vs. Other Programming Languages: A Comparison Apr 19, 2025 am 12:22 AM

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages ​​such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages ​​have advantages in their respective fields such as data analytics, enterprise applications, and system programming.

How does MySQL index cardinality affect query performance? How does MySQL index cardinality affect query performance? Apr 14, 2025 am 12:18 AM

MySQL index cardinality has a significant impact on query performance: 1. High cardinality index can more effectively narrow the data range and improve query efficiency; 2. Low cardinality index may lead to full table scanning and reduce query performance; 3. In joint index, high cardinality sequences should be placed in front to optimize query.

See all articles