一.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?
- #include "person.h"
- #include
- #include
- #include
- #include
- #include
- 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"
- 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
- while ((record = mysql_fetch_row(results))){
- cout
- }
- mysql_close(con);
- return 0;
- }
#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; }
正常情况下编译并运行就可以了。
但是有的时候会提示
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返回给客户端。
查看以上各编码的命令
- mysql> SHOW VARIABLES LIKE 'character%';
就可以看到character_set_server、character_set_connection、character_set_results等的值。
主要是理解上述所说的mysql字符编码转换的步骤,这样就能控制不会出现乱码问题。

MySQLstringtypesimpactstorageandperformanceasfollows:1)CHARisfixed-length,alwaysusingthesamestoragespace,whichcanbefasterbutlessspace-efficient.2)VARCHARisvariable-length,morespace-efficientbutpotentiallyslower.3)TEXTisforlargetext,storedoutsiderows,

MySQLstringtypesincludeVARCHAR,TEXT,CHAR,ENUM,andSET.1)VARCHARisversatileforvariable-lengthstringsuptoaspecifiedlimit.2)TEXTisidealforlargetextstoragewithoutadefinedlength.3)CHARisfixed-length,suitableforconsistentdatalikecodes.4)ENUMenforcesdatainte

MySQLoffersvariousstringdatatypes:1)CHARforfixed-lengthstrings,2)VARCHARforvariable-lengthtext,3)BINARYandVARBINARYforbinarydata,4)BLOBandTEXTforlargedata,and5)ENUMandSETforcontrolledinput.Eachtypehasspecificusesandperformancecharacteristics,sochoose

TograntpermissionstonewMySQLusers,followthesesteps:1)AccessMySQLasauserwithsufficientprivileges,2)CreateanewuserwiththeCREATEUSERcommand,3)UsetheGRANTcommandtospecifypermissionslikeSELECT,INSERT,UPDATE,orALLPRIVILEGESonspecificdatabasesortables,and4)

ToaddusersinMySQLeffectivelyandsecurely,followthesesteps:1)UsetheCREATEUSERstatementtoaddanewuser,specifyingthehostandastrongpassword.2)GrantnecessaryprivilegesusingtheGRANTstatement,adheringtotheprincipleofleastprivilege.3)Implementsecuritymeasuresl

ToaddanewuserwithcomplexpermissionsinMySQL,followthesesteps:1)CreatetheuserwithCREATEUSER'newuser'@'localhost'IDENTIFIEDBY'password';.2)Grantreadaccesstoalltablesin'mydatabase'withGRANTSELECTONmydatabase.TO'newuser'@'localhost';.3)Grantwriteaccessto'

The string data types in MySQL include CHAR, VARCHAR, BINARY, VARBINARY, BLOB, and TEXT. The collations determine the comparison and sorting of strings. 1.CHAR is suitable for fixed-length strings, VARCHAR is suitable for variable-length strings. 2.BINARY and VARBINARY are used for binary data, and BLOB and TEXT are used for large object data. 3. Sorting rules such as utf8mb4_unicode_ci ignores upper and lower case and is suitable for user names; utf8mb4_bin is case sensitive and is suitable for fields that require precise comparison.

The best MySQLVARCHAR column length selection should be based on data analysis, consider future growth, evaluate performance impacts, and character set requirements. 1) Analyze the data to determine typical lengths; 2) Reserve future expansion space; 3) Pay attention to the impact of large lengths on performance; 4) Consider the impact of character sets on storage. Through these steps, the efficiency and scalability of the database can be optimized.


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

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

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

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version
God-level code editing software (SublimeText3)

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),
