Linux下C語言操作資料庫,linuxc語言資料庫

來源:互聯網
上載者:User

Linux下C語言操作資料庫,linuxc語言資料庫

MySQL是Linux系統下廣泛使用的開源免費資料庫,是Linux應用程式資料儲存的首選。

在Ubuntu系統下安裝MySQL,可以在終端提示符中運行下列命令:

$sudo apt-get install mysql-server mysql-client

一旦安裝完成,MySQL伺服器應該自動啟動,預設的MySQL安裝後使用者為root,安裝過程中會提示你enter password,這個密碼便是你以後登陸資料庫所需的密碼。

MySQL可以用不同的語言進行訪問,其中包括C,C++,JAVA,Perl,Python,PHP等。在用C語言訪問MySQL資料庫之前,需要先安裝MySQL的開發庫:

$sudo apt-get install libmysqlclient15-dev

安裝完成後,在/uer/include/mysql下,包涵了C語言操作MySQL所需的標頭檔:mysql.h;

從C向一個MySQL資料庫的串連包括兩步:

1.初始化一個MySQL結構。

2.進行串連

下面給出一個簡單的執行個體

檔案名稱connect.c

#include <stdlib.h>#include <stdio.h>#include <mysql/mysql.h>MYSQL *conn_ptr;int main(){conn_ptr = mysql_init(NULL);if(!conn_ptr){fprintf(stderr, "mysql_init failed!\n");return -1;}conn_ptr = mysql_real_connect(conn_ptr,"localhost","root","acm","testdb",0,NULL,0);if(conn_ptr)printf("Connection succeed!\n");else{printf("Connection failed\n");return -2;}mysql_close(conn_ptr);printf("Connection closed.\n");return 0;}

由於要用到mysql檔案,因此編譯時間需要指定,在終端編譯時間命令如下:

gcc -I/usr/include/mysql connect1.c -L/usr/lib/mysql -lmysqlclient -o connect1

程式執行結果如下:

Connection succeed!

Connection closed.

可見,串連一個資料庫是非常簡單的。


相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.