linux_connect_mysql

  原文来自 https://www.cnblogs.com/lywy510/p/3615710.html

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <string.h>
 4 
 5 #include <mysql/mysql.h>
 6 
 7 MYSQL *g_conn;
 8 MYSQL_RES *g_res;
 9 MYSQL_ROW g_row;
10 
11 #define MAX_BUF_SIZE 1024
12 
13 const char *g_host_name = "localhost";
14 const char *g_user_name = "root";
15 const char *g_password = "Ll123456..";
16 const char *g_db_name = "c_test";
17 const unsigned int g_db_port = 3306;
18 
19 void print_mysql_error(const char *msg) {
20     if (msg) 
21         printf("%s:%s\n",msg,mysql_error(g_conn));
22     else 
23         puts(mysql_error(g_conn));
24 }
25 
26 int executesql(const char *sql) {
27     if (mysql_real_query(g_conn,sql,strlen(sql))) 
28         return -1;
29     
30     return 0;
31 }
32 
33 int init_mysql() {
34     g_conn = mysql_init(NULL);
35     if (!mysql_real_connect(g_conn,g_host_name,g_user_name,g_password,g_db_name,g_db_port,NULL,0))
36         return -1;
37     
38     return 0;
39 }
40 
41 int main() 
42 {
43     printf("hello world\n");
44     if (init_mysql())
45         print_mysql_error(NULL);
46     char sql[MAX_BUF_SIZE];
47     if (executesql(sql))
48         print_mysql_error(NULL);
49     if (executesql("select * from user;"))
50         print_mysql_error(NULL);
51 
52     g_res = mysql_store_result(g_conn); 
53     int iNum_rows = mysql_num_rows(g_res); 
54     int iNum_fields = mysql_num_fields(g_res);
55     printf("line = %d\t constent = %d\n", iNum_rows, iNum_fields);
56     puts("id\tname\n");
57 
58     while ((g_row=mysql_fetch_row(g_res))) 
59         printf("%s\t%s\n", g_row[0], g_row[1]);
60 
61     mysql_free_result(g_res);
62     mysql_close(g_conn);
63     return 0;
64 }
View Code

 

编译命令

 

mysql 库文件自己找一下, 一般会使 mysql-dev.....

希望对你有用

 

posted @ 2019-01-14 23:03  NorseLZJ  阅读(421)  评论(0编辑  收藏  举报