c++操作MySQLデータベースインスタンス
5382 ワード
直接コードをつけます!!!
#include
#include
#include
#include
#include
#include
using namespace std;
int main()
{
const char user[] = "root"; //username
const char pswd[] = "123456"; //password
const char host[] = "localhost"; //or"127.0.0.1"
const char database[] = "facedb"; //database
unsigned int port = 3306; //server port
MYSQL myCont;
MYSQL_RES *result=NULL;
MYSQL_ROW row;
MYSQL_FIELD *fd=NULL;
char column[32][32];
int res;
unsigned long num_col;
unsigned long num_row;
int i = 0;
mysql_init(&myCont);
char sql[1000];
if (mysql_real_connect(&myCont, host, user, pswd, database, port, NULL, 0))
{
cout << "connect success!!!!!" << endl;
}
else
{
cout << "connect fail!!!" << endl;
}
mysql_query(&myCont,"SET NAMES GBK");//
strcpy(sql, "select * from result");
res = mysql_real_query(&myCont, sql, strlen(sql));
result = mysql_store_result(&myCont);
if (!result)
{
cout << " !!" << endl;
}
num_row = (unsigned long)mysql_num_rows(result); //
num_col = (unsigned long)mysql_num_fields(result);//
cout << "number of row:" << num_row << endl;
cout << "number of col:" << num_col << endl;
//while (fd= mysql_fetch_field(result)) //
//{
// printf("%s\t", fd->name);
//}
while (fd = mysql_fetch_field(result))// , 。
{
strcpy(column[i], fd->name);//
printf("%s\t", column[i]);
i++;
}
printf("
");
while (row = mysql_fetch_row(result))//
{
for (i = 0; i < num_col; i++)
{
printf("%s\t", row[i]);
}
printf("
");
}
mysql_free_result(result);//
mysql_close(&myCont);//
return 0;
}