以下是从书上总结下来的,c语言操作mysql的比较全面的例子。可以看出基本的使用过程。
#include < stdio.h>
#include < stdlib.h>
#include < mysql.h>
MYSQL *conn;
MYSQL_RES *res;
MYSQL_ROW row;
int main(void) {
puts("mysql demo by guo8113:");
printf("client info :%s\n",mysql_get_client_info());
char *server = "localhost";
char *user = "root";
char *password = "8113";
char *database = "test";
//1.初始化链接
conn = mysql_init(NULL);
//2.设置选项(可选)
unsigned int timeout = 100;
if( mysql_options(conn,MYSQL_OPT_CONNECT_TIMEOUT,(const char*)&timeout) )
{//调用成功返回0
fprintf(stderr,"Set option error %d:%s\n",
mysql_errno(conn),mysql_error(conn));
}
//3建立链接
if (!mysql_real_connect(conn, server,
user, password, database, 0, NULL, 0))
{
fprintf(stderr,"Connection failed\n");
if(mysql_errno(&conn))
{
fprintf(stderr,"Connection error %d:%s\n",
mysql_errno(conn),mysql_error(conn));
}
exit(1);
}
printf("server info :%s\n",mysql_get_server_info(conn));
printf("host info :%s\n",mysql_get_host_info(conn));
//4操作
if (mysql_query(conn, "show tables"))
{//执行sql语句,语句不需要以分号结束
fprintf(stderr, "%s\n", mysql_error(conn));
exit(1);
}
//读取返回信息并显示
res = mysql_use_result(conn);
printf("MySQL Tables in mysql database:\n");
while ((row = mysql_fetch_row(res)) != NULL)
printf("%s \n", row[0]);
mysql_free_result(res);
mysql_query(conn,"INSERT INTO children(fname,age) VALUES('guo',23)");//这里方便演示不设异常处理
//INSERT,DELETE,UPDATE不返回任何数据
printf("Inserted %lu rows\n",(unsigned long)mysql_affected_rows(conn));
mysql_query(conn,"SELECT childno,fname,age FROM children");
//select返回数据,同样用MYSQL_RES来
//res = mysql_store_result(conn);
res = mysql_use_result(conn);
//与mysql_store_result,
//区别在于_use_result不能与mysql_data_seek,mysql_row_seek,mysql_row_tell一起使用
if(res){
printf("SELECT:Retrieved %lu rows\n",(unsigned long)mysql_num_rows(res));
while((row=mysql_fetch_row(res))){
int field_count=0;
while(field_count< mysql_field_count(conn)){//获得数据域(列)
printf("%s ",row[field_count]);
field_count++;
}
printf("\n");
}
}
mysql_free_result(res);//完成对数据操作
//5.关闭访问
mysql_close(conn);
return EXIT_SUCCESS;
}
#include < stdio.h>
#include < stdlib.h>
#include < mysql.h>
int main(void) {
//1.初始化链接
//2.设置选项(可选)
//3建立链接
//4操作
//5.关闭访问
}