环境搭建
我用的是Visual Studio 2015+MySQL / Codeblocks 16+MySQL的环境,具体环境的搭建见:
http://blog.csdn.net/beiwei_31/article/details/76665035
C API
C API代码是与MySQL一起提供的,但因为我的MySQL和VS版本不兼容,所以用Connector/C做了连接,从而允许C/C++程序访问数据库。C API库的说明见:
http://blog.csdn.net/beiwei_31/article/details/76669079
MySQL连接和增删改查操作
1. 首先新建工程,新建main.cpp, 在头文件中要包含mysql.h文件,还有winsock2.h头文件(网上有人说需要这个文件进行mysql连接和socket);
#include <iostream>
#include <stdio.h>
#include <winsock2.h> //socket,连接MySQL时也要用到
#include <mysql.h> //包含MYSQL所需的头文件
using namespace std;
2. 设置连接参数,包括服务器地址、用户名、密码,要连接的数据库名等。以下内容全部包含在main函数中。
//const char *host = "localhost"; //本地MySQL服务器
const char *host = "127.0.0.1"; //本地MySQL服务器
const char *user = "root"; //连接MySQL的用户名
const char *passwd = "llll"; //MySQL服务器密码
const char *db = "test"; //要连接的数据库名
unsigned int port = 3306;//MySQL服务器的端口,默认是3306
const char *unix_socket = NULL; //unix_socket是unix下的,在windows下就把它设置为NULL
unsigned long client_flag = 0; //一般为0
3. 建立与数据库的连接
MYSQL mysql, *sock; //mysql连接句柄
MYSQL_RES *result; //保存结果集
MYSQL_ROW row; //存储结果集中的一行
mysql_init(&mysql);//连接数据库之前必须使用这个函数来初始化
//和数据库服务器建立连接
sock=mysql_real_connect(&mysql, host, user, passwd, db, port, unix_socket, client_flag);
if (sock == NULL) //连接MySQL失败
{
cout << "Failed to connect.";
cout << mysql_error(&mysql) << endl;
mysql_close(&mysql);
exit(1);
}
else
{
cout << "Successful! Connecting to MySQL... " << endl;
}
4. 数据库查询操作
//查询 数据库数据
const char * i_query = "select * from student";//查询语句
if (mysql_query(&mysql, i_query) != 0) //如果连接成功,则开始查询.如果查询成功,返回0,否则返回非0
{
cout << "Query Failed." << endl;
exit(1);
}
else
{
result = mysql_store_result(&mysql);
if (result == NULL) //保存查询的结果集
{
cout << "Failed to save result set." << endl;
exit(1); //异常,退出程序
}
else
{
cout << "Query data in mysql database student, Done." << endl;
/*
while ((row = mysql_fetch_row(result)) != NULL) //读取结果集中的数据,返回的是下一行,因为保存结果集时,当前的游标在第一行之前。
{
cout << row[0] << ' '<< row[1] <<' '<<row[2]<<' '<<row[3]<<endl;//打印当前行的四列数据
}
*/
}
}
5.数据库插入记录操作
//插入 新的表记录
const char *i_insert = "insert into student values ('030123','Liming','18023430923','USTC')";
if (mysql_query(&mysql, i_insert) != 0)
{
cout << "Failed to insert data into student." << endl;
}
else
{
cout << "Insert new data into database student,Done." << endl;
}
6. 数据库修改操作
//修改 表记录
const char *i_set = "update student set contact='15950529999' where student_number='040101';";
if (mysql_query(&mysql, i_set) != 0)
{
cout << "Failed to set new value." << endl;
}
else
{
cout << "Update database student,Done." << endl;
}
7. 数据库删除操作
//删除 表记录
const char *i_delete = "delete from student where student_number='030123';";
if (mysql_query(&mysql, i_delete) != 0)
{
cout << "Failed to delete table entries." << endl;
}
else
{
cout << "Delete data from database student,Done." << endl;
}
8. 关闭数据库连接
mysql_free_result(result);//释放结果集;
mysql_close(sock);//关闭连接