经常用到C语言去控制MYSQL,以下是个人写的
我的mysql目录(从网上下载之后直接解包后的目录),最近的Mysql不用进行安装
[www@zhoubc mysql]$ ls /home/zhoubaochuan/mysql-5.5.11-linux2.6-i686/lib/ libmysqlclient.a libmysqlclient_r.so libmysqlclient_r.so.18.0.0 libmysqlclient.so.18 libmysqld.a libmysqlservices.a plugin libmysqlclient_r.a libmysqlclient_r.so.18 libmysqlclient.so libmysqlclient.so.18.0.0 libmysqld-debug.a libtcmalloc_minimal.so [www@zhoubc mysql]$ ls /home/zhoubaochuan/mysql-5.5.11-linux2.6-i686/include/ decimal.h m_string.h my_config.h my_global.h mysql mysql_embed.h my_sys.h plugin.h sslopt-longopts.h errmsg.h my_alloc.h my_dbug.h my_list.h mysql_com.h mysql.h my_xml.h sql_common.h sslopt-vars.h keycache.h my_attribute.h my_dir.h my_net.h mysqld_ername.h mysql_time.h plugin_audit.h sql_state.h typelib.h m_ctype.h my_compiler.h my_getopt.h my_pthread.h mysqld_error.h mysql_version.h plugin_ftparser.h sslopt-case.h
1.编写main.c
#include <stdio.h> #include <stdlib.h> #include <mysql.h> int main(int argc, char *argv[]){ const char *host = "localhost"; const char *user = "root"; const char *password = ""; const char *db = "mysql"; MYSQL conn; printf("Start Mysql init=====================================\n"); mysql_init(&conn); /* 初始化 */ if (!mysql_real_connect(&conn, host, user, password, db, 0, NULL, 0)){ printf("Open the %s connect is failure!", mysql_error(&conn)); return -1; } printf("Start Mysql query=====================================\n"); /* 查询 */ char *sql = "select * from user"; if (mysql_query(&conn, sql) != 0){ printf("%s \n", mysql_errno(&conn), mysql_error(&conn)); } MYSQL_RES *rs = mysql_store_result(&conn); /* 获取结果 */ MYSQL_ROW row; while(row = mysql_fetch_row(rs)){ /* 一行一行的记录 */ printf("%s===============%s\n",row[0],row[1]); } mysql_free_result(rs); mysql_close(&conn); return 0; }
2.编写Makefile
CC=gcc 1: $(CC) main.c -L/home/zhoubaochuan/mysql-5.5.11-linux2.6-i686/lib -lmysqlclient -I/home/zhoubaochuan/mysql-5.5.11-linux2.6-i686/include -Wl,-rpath,/home/zhoubaochuan/mysql-5.5.11-linux2.6-i686/lib -o mysql
3.编译
[www@zhoubc mysql]$ make gcc main.c -L/home/zhoubaochuan/mysql-5.5.11-linux2.6-i686/lib -lmysqlclient -I/home/zhoubaochuan/mysql-5.5.11-linux2.6-i686/include -Wl,-rpath,/home/zhoubaochuan/mysql-5.5.11-linux2.6-i686/lib -o mysql
4.执行代码
[www@zhoubc mysql]$ ./mysql Open the Can't connect to local MySQL server through socket '/tmp/mysql.sock' (111) connect is failure!
错误:MYSQL SERVER未启动
5.启动MYSQL SERVER
[root@zhoubc mysql-5.5.11-linux2.6-i686]# /etc/init.d/mysql.server start Starting MySQL [确定]
6.再次执行
[www@zhoubc mysql]$ ./mysql Start Mysql init===================================== Start Mysql query===================================== localhost===============root zhoubc===============root 127.0.0.1===============root ::1===============root localhost=============== zhoubc===============