怎样在C++中调用MYSQL数据库中的数据

2024-11-20 08:36:29
推荐回答(3个)
回答1:

1、用CAPI连接MySQL数据库有两个步骤:
1)初始化一个连接句柄
2)建立连接
所用到的函数如下:
MYSQL *mysql_init(MYSQL *connection); // 初始化连接句柄
//成功返回MySQL结构指针,失败返回NULL

MYSQL *mysql_real_connect(MYSQL *connection,
const char *server_host,
const char *sql_user_name,
const char *sql_password,
const char *db_name,
unsigned int port_number,
const char *unix_socket_name,
unsigned int flags); //建立连接
//成功返回MySQL结构指针,失败返回NULL
以下是完整实例:

#include
#include
#include
#include

using namespace std;

void mysql_err_function(MYSQL * connection);

int main()
{
//freopen("input.txt","r",stdin);

MYSQL * connection;
connection = mysql_init(NULL);

if (!connection)
{
cout << "mysql_init failed!" << endl;

exit(-1);
}

if (!mysql_real_connect(connection,"localhost","root","123456","test",0,NULL,0))
{
cout << "Connection To MySQL failed!" << endl;
mysql_err_function(connection);
}

cout << "Connection To MySQL Server is Success..." << endl;

string str;
getline(cin,str);

int res = 0;
int affected_count = 0;
while (str != "close" && str != "" && !res)
{
res = mysql_query(connection,str.c_str());

affected_count += mysql_affected_rows(connection);

if (res)
{
if (mysql_errno(connection))
{
cout << "Error " << mysql_errno(connection) << " : "
<< mysql_error(connection) << '\n' << endl;
break;
}
}
getline(cin,str);
}

cout << "Have affected " << affected_count << " rows!" << endl;

mysql_close(connection);
cout << "Connection To MySQL Server is closed..." << endl;

return 0;
}

void mysql_err_function(MYSQL * connection)
{
if (mysql_errno(connection))
{
cout << "Error " << mysql_errno(connection) << " : "
<< mysql_error(connection) << endl;

exit(-1);
}
}

回答2:

建立一个空的控制台程序,建立一个cpp文件,在其中加入如下代码。代码部分:

Cpp代码
#include
//定义socket
#include
#include"mysql.h"
//#pragma comment( lib, "libmysql.lib");
//此句话和在附加依赖项中增加libmysql.lib 的功能一样

usingnamespace std;
int main(char **args)
{
MYSQL mysql;
mysql_init(&mysql);
if (mysql_real_connect(&mysql,"localhost","root","","test",3306,0,0))
{
cout<<"ok"< return 0;
}
else
{
int i = mysql_errno(&mysql);
constchar * s = mysql_error(&mysql);
cout << s< }
}

#include
//定义socket
#include
#include"mysql.h"
//#pragma comment( lib, "libmysql.lib");
//此句话和在附加依赖项中增加libmysql.lib 的功能一样

usingnamespace std;
int main(char **args)
{
MYSQL mysql;
mysql_init(&mysql);
if (mysql_real_connect(&mysql,"localhost","root","","test",3306,0,0))
{
cout<<"ok"< return 0;
}
else
{
int i = mysql_errno(&mysql);
constchar * s = mysql_error(&mysql);
cout << s< }
} 相关设置:
1、附加包含头文件的目录,include就是mysql-5.0.27-win32\Include文件夹。
2、附加库目录,MySql lib中的文件就是mysql-5.0.27-win32\lib\opt中的文件
3、附加依赖项,名称为libmysql.lib
4、将libmysql.dll拷贝到debug文件夹中,libmysql.dll在lib文件夹中有

回答3:

include "mysql.h"

然后调用mysql API库