MySQLデータベース操作例C++
環境設定:
MySQLのインストールが完了すると、ディレクトリのincludeディレクトリのlibmysqlがインストールされます.libファイルは、VS 2008インストールディレクトリのVClibの下にコピーし、プロジェクト-オプション-c/c++-通常の追加包含ディレクトリおよびリンク-通常の追加ライブラリディレクトリに「c:MySQLinclude」を追加し、リンク-入力の追加依存項目に「libmysql.lib」を追加することで、コンパイラにmysqlを見つけることができます.hヘッダファイルであり、プログラムでc言語のmysql APIを使用してデータベースを操作することができる.(MySQLインストールディレクトリにincludeディレクトリがない場合は、MySQL公式サイトでMySQL connector for Cをダウンロードしてインストールし、includeディレクトリパスを変更できます)
記事の出典:http://www.cnblogs.com/lovebread/archive/2009/11/24/1609936.html
MySQLのインストールが完了すると、ディレクトリのincludeディレクトリのlibmysqlがインストールされます.libファイルは、VS 2008インストールディレクトリのVClibの下にコピーし、プロジェクト-オプション-c/c++-通常の追加包含ディレクトリおよびリンク-通常の追加ライブラリディレクトリに「c:MySQLinclude」を追加し、リンク-入力の追加依存項目に「libmysql.lib」を追加することで、コンパイラにmysqlを見つけることができます.hヘッダファイルであり、プログラムでc言語のmysql APIを使用してデータベースを操作することができる.(MySQLインストールディレクトリにincludeディレクトリがない場合は、MySQL公式サイトでMySQL connector for Cをダウンロードしてインストールし、includeディレクトリパスを変更できます)
#include <Windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <mysql.h>
#include <iostream>
using namespace std;
int main()
{
const char user[] = "root"; //username
const char pswd[] = "root"; //password
const char host[] = "localhost"; //or"127.0.0.1"
const char table[] = "test"; //database
unsigned int port = 3306; //server port
MYSQL myCont;
MYSQL_RES *result;
MYSQL_ROW sql_row;
MYSQL_FIELD *fd;
char column[32][32];
int res;
mysql_init(&myCont);
if(mysql_real_connect(&myCont,host,user,pswd,table,port,NULL,0))
{
cout<<"connect succeed!"<<endl;
mysql_query(&myCont, "SET NAMES GBK"); // , cmd
res=mysql_query(&myCont,"select * from samples");//
if(!res)
{
result=mysql_store_result(&myCont);// result
if(result)
{
int i,j;
cout<<"number of result: "<<(unsigned long)mysql_num_rows(result)<<endl;
for(i=0;fd=mysql_fetch_field(result);i++)//
{
strcpy(column[i],fd->name);
}
j=mysql_num_fields(result);
for(i=0;i<j;i++)
{
printf("%s\t",column[i]);
}
printf("
");
while(sql_row=mysql_fetch_row(result))//
{
for(i=0;i<j;i++)
{
printf("%s
",sql_row[i]);
}
printf("
");
}
}
}
else
{
cout<<"query sql failed!"<<endl;
}
}
else
{
cout<<"connect failed!"<<endl;
}
if(result!=NULL) mysql_free_result(result);//
mysql_close(&myCont);//
return 0;
}
記事の出典:http://www.cnblogs.com/lovebread/archive/2009/11/24/1609936.html