search
HomeDatabaseMysql TutorialC连接MySQL数据库开发之Windows环境搭建及测试_MySQL

<strong>一、开发环境</strong>

Win8.1 64位、VS2013、MySQL5.5.3764位

MySQL安装目录为:C:/Program Files/MySQL/MySQL Server 5.5

<strong>二、配置工程环境</strong>

首先创建一个控制台空项目,打开VS2013,文件--> 新建项目 --> 常规 --> 选择“空项目”



      因为我们要使用MySQL数据库的API接口编程,所以需要将工程的附加头文件搜索目录和附件库文件搜索目录,指向MySQL安装目录对应的位置,下面是我机子上mysql库和头文件目录:



将VS2013工程的附加头文件目录和附加库目录指向上面两个目录。


1> 配置头文件目录

打开工程配置属性窗口--> C/C++ --> 常规 --> 附加包含目录,把mysql的include目录添加到附加包含目录中,如下图所示:






2> 配置库文件目录

打开工程配置窗口--> 链接器--> 常归 --> 附加库目录,把mysql的lib目录添加到附加库目录中,如下图所示:



打开工程配置窗口--> 链接器--> 输入-->附中依赖项,打libmysql.lib静态库添加到工程编译依赖项,如下图所示:






将libmysql.dll动态库拷贝到工程的根目录或Debug目录下:




<strong>三、测试开发环境</strong>
#include <stdio.h>#include <stdlib.h>#include <windows.h>#include <mysql.h>void testQuery(MYSQL *mysql);	// 测试查询数据void main(){	MYSQL *mysql = NULL;	/*初始化MYSQL连接句柄*/	mysql = mysql_init((MYSQL *)0);	if (!mysql)	{		return;	}	/*		连接数据库,连接成功返回conn,否则返回NULL		参数1:mysql_init初始化数据库返回的MYSQL句柄		参数2:数据库服务器地址		参数3:数据库用户名		参数4:数据库密码		参数5:数据库名称		参数6:数据库端口,为0表示默认3306		参数7:如果unix_socket不是NULL,字符串指定套接字或应该被使用的命名管道。注意host参数决定连接的类型		参数8:通常是0	*/	mysql = mysql_real_connect(mysql, "localhost","root", "root", 		"test", 0, NULL, 0);	if (mysql)	{		printf("connection succellfull the database!/n");	}	else	{		printf("connection error:%d, %s/n",mysql_errno(mysql), mysql_error(mysql));	}	// 查询数据	testQuery(mysql);	// 关闭连接	mysql_close(mysql);	system("pause");}// 测试查询void testQuery(MYSQL *mysql){	MYSQL_ROW row;	MYSQL_RES *res = NULL;	MYSQL_FIELD *fields = NULL;	int i, field_count;	char *sql = "select * from t_user";	int flag = mysql_real_query(mysql, sql, (unsigned long)strlen(sql));	if (flag)	{		printf("Query error:%d, %s/n",mysql_errno(mysql), mysql_error(mysql));		return;	}	// 将查询结果读到内存当中	res = mysql_store_result(mysql);	// 获取结果集中的所有字段	fields = mysql_fetch_fields(res);	// 字段数量	field_count = mysql_field_count(mysql);	for (i = 0; i <p><strong>mysql测试数据及表结构:</strong></p>
<pre class="brush:php;toolbar:false">DROP TABLE IF EXISTS `t_user`;CREATE TABLE `t_user` (`id` int(11) NOT NULL AUTO_INCREMENT,`name` varchar(32) DEFAULT NULL,`age` int(11) DEFAULT NULL,`address` varchar(100) DEFAULT NULL,PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;LOCK TABLES `t_user` WRITE;INSERT INTO `t_user` VALUES (1,'zhangsan',22,'hunan'),(2,'lisi',30,'beijin');UNLOCK TABLES;
测试结果:


小结配置步聚:

1> 安装mysql

2> 创建VS工程,配置工程头文件(mysql.h所在目录)和库文件(libmysql.lib所在目录)附加目录,指向mysql对应的目录

3> 将libmysql.dll动态库拷贝到工程根目录或Debug目录

4> 编写测试程序,验证C连接Mysql数据库

----------------------------------------------------------------------优雅的分割线------------------------------------------------------------------------------------

常见错误:

1、main.obj : error LNK2019: 无法解析的外部符号 mysql_init。。。。。


原因是没有在工程当中添加libmysql.lib配置,配置库文件目录

2、无法启动此程序,因为计算机中丢失libmyslq.dll。。。。


将libmysql.dll动态库拷贝到工程的根目录或Debug目录下。

3、未引入windows.h头文件,因为在windows连接mysql是通过socket方式与数据库进行通信的


4、main.obj : error LNK2019: 无法解析的外部符号 _mysql_init@4,该符号在函数 _main 中被引用.....

数据库位数与编译位数不一致,导致在链接时mysql的库函数找不到,比如:我的mysql是64位,提供的库当然是64位的,如果你在VS上用32位的平台去编译就会造成链接时出错。


修改编译平台,工程-->属性-->配置管理器-->在解决方案的工程列表中选择对应的项目,并将其修改成32位或64位,如果没有就新建一个。


工程源码下载:Windows平台C连接MySQL数据库

参考文档:

C/C++连接MySql数据库

Statement
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
What Are the Limitations of Using Views in MySQL?What Are the Limitations of Using Views in MySQL?May 14, 2025 am 12:10 AM

MySQLviewshavelimitations:1)Theydon'tsupportallSQLoperations,restrictingdatamanipulationthroughviewswithjoinsorsubqueries.2)Theycanimpactperformance,especiallywithcomplexqueriesorlargedatasets.3)Viewsdon'tstoredata,potentiallyleadingtooutdatedinforma

Securing Your MySQL Database: Adding Users and Granting PrivilegesSecuring Your MySQL Database: Adding Users and Granting PrivilegesMay 14, 2025 am 12:09 AM

ProperusermanagementinMySQLiscrucialforenhancingsecurityandensuringefficientdatabaseoperation.1)UseCREATEUSERtoaddusers,specifyingconnectionsourcewith@'localhost'or@'%'.2)GrantspecificprivilegeswithGRANT,usingleastprivilegeprincipletominimizerisks.3)

What Factors Influence the Number of Triggers I Can Use in MySQL?What Factors Influence the Number of Triggers I Can Use in MySQL?May 14, 2025 am 12:08 AM

MySQLdoesn'timposeahardlimitontriggers,butpracticalfactorsdeterminetheireffectiveuse:1)Serverconfigurationimpactstriggermanagement;2)Complextriggersincreasesystemload;3)Largertablesslowtriggerperformance;4)Highconcurrencycancausetriggercontention;5)M

MySQL: Is it safe to store BLOB?MySQL: Is it safe to store BLOB?May 14, 2025 am 12:07 AM

Yes,it'ssafetostoreBLOBdatainMySQL,butconsiderthesefactors:1)StorageSpace:BLOBscanconsumesignificantspace,potentiallyincreasingcostsandslowingperformance.2)Performance:LargerrowsizesduetoBLOBsmayslowdownqueries.3)BackupandRecovery:Theseprocessescanbe

MySQL: Adding a user through a PHP web interfaceMySQL: Adding a user through a PHP web interfaceMay 14, 2025 am 12:04 AM

Adding MySQL users through the PHP web interface can use MySQLi extensions. The steps are as follows: 1. Connect to the MySQL database and use the MySQLi extension. 2. Create a user, use the CREATEUSER statement, and use the PASSWORD() function to encrypt the password. 3. Prevent SQL injection and use the mysqli_real_escape_string() function to process user input. 4. Assign permissions to new users and use the GRANT statement.

MySQL: BLOB and other no-sql storage, what are the differences?MySQL: BLOB and other no-sql storage, what are the differences?May 13, 2025 am 12:14 AM

MySQL'sBLOBissuitableforstoringbinarydatawithinarelationaldatabase,whileNoSQLoptionslikeMongoDB,Redis,andCassandraofferflexible,scalablesolutionsforunstructureddata.BLOBissimplerbutcanslowdownperformancewithlargedata;NoSQLprovidesbetterscalabilityand

MySQL Add User: Syntax, Options, and Security Best PracticesMySQL Add User: Syntax, Options, and Security Best PracticesMay 13, 2025 am 12:12 AM

ToaddauserinMySQL,use:CREATEUSER'username'@'host'IDENTIFIEDBY'password';Here'showtodoitsecurely:1)Choosethehostcarefullytocontrolaccess.2)SetresourcelimitswithoptionslikeMAX_QUERIES_PER_HOUR.3)Usestrong,uniquepasswords.4)EnforceSSL/TLSconnectionswith

MySQL: How to avoid String Data Types common mistakes?MySQL: How to avoid String Data Types common mistakes?May 13, 2025 am 12:09 AM

ToavoidcommonmistakeswithstringdatatypesinMySQL,understandstringtypenuances,choosetherighttype,andmanageencodingandcollationsettingseffectively.1)UseCHARforfixed-lengthstrings,VARCHARforvariable-length,andTEXT/BLOBforlargerdata.2)Setcorrectcharacters

See all articles

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 Article

Hot Tools

MinGW - Minimalist GNU for Windows

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.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool