准备:
系统: ubuntu12.04
工具: gcc,mysql,libmysqlclient-dev
测试代码(文件名:con_mysql.c):
#include<mysql/mysql.h> #include<stdio.h> main() { MYSQL *conn; MYSQL_RES *res; MYSQL_ROW row; char *server = "localhost"; char *user = "root"; char *password = "123456"; /* set me first */ char *database = "mysql"; char *query = "select Host,User,Password from user"; int t, r; conn = mysql_init(NULL); if(!mysql_real_connect(conn, server, user, password, database, 0, NULL, 0)) { printf("Error connecting to database: %s\n", mysql_error(conn)); } else { printf("Connected....\n"); } t = mysql_query(conn, query); if(t) { printf("Error making query: %s\n", mysql_error(conn)); } else { printf("Query made...\n"); res = mysql_use_result(conn); if(res) { for(r=0; r<=mysql_field_count(conn); r++) { row = mysql_fetch_row(res); if(row<0) break; for(t=0; t<mysql_num_fields(res); t++) printf("%s", row[t]); printf("\n"); } } mysql_free_result(res); } mysql_close(conn); return 0; }
编译:
gcc con_mysql.c -L /usr/lib/mysql/ -lmysqlclient -o con_mysql
执行:
./con_mysql
结果:
Connected.... Query made... localhostroot*6BB4837EB74329105EE4568DDA7DC67ED2CA2AD9 ubunturoot 127.0.0.1root ::1root
本文出自 “9645582” 博客,请务必保留此出处http://9655582.blog.51cto.com/9645582/1794151
原文地址:http://9655582.blog.51cto.com/9645582/1794151