Howto: Connect MySQL server using C program API under Linux or UNIX

这篇文章编译C程序部分与众不同。

原文地址:http://www.cyberciti.biz/tips/linux-unix-connect-mysql-c-api-program.html

-----

From my mailbag:

How do I write a C program to connect MySQL database server?

MySQL database does support C program API just like PHP or perl.

The C API code is distributed with MySQL. It is included in the mysqlclient library and allows C programs to access a database.

Many of the clients in the MySQL source distribution are written in C. If you are looking for examples that demonstrate how to use the C API, take a look at these clients. You can find these in the clients directory in the MySQL source distribution.

Requirements(注意了!)

Make sure you have development environment installed such as gcc, mysql development package etc. Following is the list summarize the list of packages to compile program:

  • mysql:MySQL client programs and shared library
  • mysqlclient:Backlevel MySQL shared libraries (old libs)
  • mysql-devel: Files for development of MySQL applications (a must have)
  • mysql-server: Mysql server itself
  • gcc, make and other development libs: GNU C compiler

Sample C Program

Following instructions should work on any Linux distro or UNIX computer. Here is the small program that connects to mysql server and list tables from mysql database.(download link):

/* Simple C program that connects to MySQL Database server*/
#include <mysql.h>
#include <stdio.h>
main() {
   MYSQL *conn;
   MYSQL_RES *res;
   MYSQL_ROW row;
   char *server = "localhost";
   char *user = "root";
   char *password = "PASSWORD"; /* set me first */
   char *database = "mysql";
   conn = mysql_init(NULL);
   /* Connect to database */
   if (!mysql_real_connect(conn, server,
         user, password, database, 0, NULL, 0)) {
      fprintf(stderr, "%s\n", mysql_error(conn));
      exit(1);
   }
   /* send SQL query */
   if (mysql_query(conn, "show tables")) {
      fprintf(stderr, "%s\n", mysql_error(conn));
      exit(1);
   }
   res = mysql_use_result(conn);
   /* output table name */
   printf("MySQL Tables in mysql database:\n");
   while ((row = mysql_fetch_row(res)) != NULL)
      printf("%s \n", row[0]);
   /* close connection */
   mysql_free_result(res);
   mysql_close(conn);
}

How do I compile and link program against MySQL libs?

MySQL comes with a special script called mysql_config. It provides you with useful information for compiling your MySQL client and connecting it to MySQL database server. You need to use following two options.
Pass --libs option - Libraries and options required to link with the MySQL client library.

$ mysql_config --libs
Output:

-L/usr/lib64/mysql -lmysqlclient -lz -lcrypt -lnsl -lm -L/usr/lib64 -lssl -lcrypto

Pass --cflags option - Compiler flags to find include files and critical compiler flags and defines used when compiling the libmysqlclient library.
$ mysql_config --cflags
Output:

-I/usr/include/mysql -g -pipe -m64 -D_GNU_SOURCE -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE -fno-strict-aliasing

You need to pass above option to GNU C compiler i.e. gcc. So to compile above program, enter:
gcc -o output-file $(mysql_config --cflags) mysql-c-api.c $(mysql_config --libs)
Now execute program:
$ ./output-file
Output:

MySQL Tables in mysql database:
columns_priv
db
func
help_category
help_keyword
help_relation
help_topic
host
tables_priv
time_zone
time_zone_leap_second
time_zone_name
time_zone_transition
time_zone_transition_type
user 

References:

  • MySQL C API - A must read - official MySQL C API documentation

-------------------------

编译时遇到的问题: undefined reference to `mysql_init' 

原因:

mysql和mysqlclient这两个library没被link到,所以去Project | Properties | C/C++ Build | Settings | Tool Settings | GCC C++ Linker | Libraries 添加mysqland mysqlclient ,重新编译,成功。


另外,上面应该在GCC C++ Linker里做,如果在GCC C++ Compiler里做的话(当然,这是不对的,因为lib文件是已经编译过的啦),就会出现stray '/' in program 错误


-----

参考:http://stackoverflow.com/questions/15745067/why-eclipse-link-fails

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
To connect to an HTTP endpoint using Java programming, you can use the HttpURLConnection class provided in the Java standard library. Here is an example code snippet: ```java import java.net.HttpURLConnection; import java.net.URL; import java.io.BufferedReader; import java.io.InputStreamReader; public class HttpExample { public static void main(String[] args) { try { // Create a URL object for the endpoint URL url = new URL("http://example.com/api/endpoint"); // Create an HttpURLConnection object HttpURLConnection con = (HttpURLConnection) url.openConnection(); // Set the request method (GET, POST, etc.) con.setRequestMethod("GET"); // Read the response from the endpoint BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); // Print the response to the console System.out.println(response.toString()); } catch (Exception e) { e.printStackTrace(); } } } ``` In this example, we create a URL object for the endpoint we want to connect to, and then create an HttpURLConnection object with that URL. We set the request method to "GET", which is the most common method for retrieving data from an HTTP endpoint. We then read the response from the endpoint using a BufferedReader, and append each line of the response to a StringBuffer. Finally, we print the response to the console. Note that this is just a basic example, and there are many different ways to connect to an HTTP endpoint in Java, depending on your specific requirements.

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值