c++ 连接mysql

闲来无事,学习一下用cpp连接myql的方法:

代码也是从网上抄的#include <iostream> #include "mysql.h" #define host "localhost" #define username "root" #define password "xxx" #define database "test" using namespace std; MYSQL *conn; int main() { MYSQL_RES *res_set; MYSQL_ROW row; unsigned int i, num_fields; MYSQL_FIELD *field; conn = mysql_init(NULL); mysql_real_connect(conn,host,username,password,database,0,NULL,0); cout << "Database Charset:" << mysql_character_set_name(conn) << endl; char * sql = "select * from mytest_table"; cout << sql << endl; mysql_query(conn, sql); res_set = mysql_store_result(conn); while((field = mysql_fetch_field(res_set))) { printf("%-15s", field->name); } printf("/n----------------------------/n"); /*** Same as above num_fields = mysql_num_fields(res_set); for(i = 0; i < num_fields; i++) { field = mysql_fetch_field_direct(res_set, i); printf("Field %u is %s/n", i, field->name); } */ while ((row = mysql_fetch_row(res_set)) != NULL) { for (i=0; i<mysql_num_fields(res_set); i++) { printf("%-15s",row[i] != NULL ? row[i] : "NULL"); } printf("/n"); } mysql_close(conn); return 0; }

 

最后编译:

g++ -I/usr/local/mysql/include/mysql -L/usr/local/mysql/lib/mysql -lmysqlclient -o aa test.cpp

你可能感兴趣的:(sql,C++,mysql,null,database,character)