MySql数据库C++访问
//在winxpsp2+devcpp4.9中编译通过
//在运行之前请先用devcpp下载相应的包
/*
Name: mysql.cpp
Copyright: 2005 Frantisek Sidak
Author: Frantisek Sidak
Date: 23.11.2005 13:00
Description: simple MySQL connection test
*/
#include <windows.h>
#include <iostream>
#include <mysql/mysql.h>
#include <stdio.h>
using namespace std;
int main()
{
//connection params
char *host = "localhost";
char *user = "root";
char *pass = "sa";
char *db = "mytry";
//sock
MYSQL *sock;
MYSQL_RES *results;
MYSQL_ROW record;
sock = mysql_init(0);
if (sock) cout << "sock handle ok!" << endl;
else {
cout << "sock handle failed!" << mysql_error(sock) << endl;
}
//connection
if (mysql_real_connect(sock, host, user, pass, db, 0, NULL, 0))
cout << "connection ok!" << endl;
else {
cout << "connection fail: " << mysql_error(sock) << endl;
}
//connection character set
cout << "connection character set: " << mysql_character_set_name(sock) << endl;
//wait for posibility to check system/mysql sockets
if(mysql_query(sock,"select name,age from db1"))
{
cout<<"very good!"<<endl;
}
results=mysql_store_result(sock);
while(record=mysql_fetch_row(results))
{
printf("%s - %s \n",record[0],record[1]);
}
mysql_free_result(results);
system("PAUSE");
//closing connection
mysql_close(sock);
return EXIT_SUCCESS;
}