linux 使用c語言串連mysql資料

來源:互聯網
上載者:User

 以下內容來自 beginning linux programming一書

c串連mysql兩步驟

1. 初始化一個串連控制代碼結構

2. 實際進行串連

#include <stdlib.h>
#include <stdio.h>
#include "mysql.h"
int main(char arc,char *argv[])
{
MYSQL *conn_ptr;

conn_ptr = mysql_init(NULL);

conn_ptr = mysql_real_connect(conn_ptr,"localhost","rick","123456",
"foo",0,NULL,0);

if(conn_ptr)
printf("connection success\n");
mysql_close(conn_ptr);
}

exit(EXIT_SUCCESS);

//錯誤處理

#include <stdlib.h>
#include <stdio.h>
#include "mysql.h"
int main(char arc,char *argv[])
{
MYSQL my_connection;
mysql_init(&my_connection);
if(mysql_real_connect(&my_connection,"localhost","rick","i don't know",
"foo",0,NULL,0))
{
printf("connection success\n");
mysql_close(&my_connection);
}
else
{
fprintf(stderr,"connection failed\n");
if(mysql_errno(&my_connection))
fprintf(stderr,"connection error %d:%s\n",mysql_errno(&my_connection),mysql_error(&my_connection));
if(mysql_errno(&my_connection))
fprintf(stderr,"connection error %d:%s\n",mysql_errno(&my_connection),mysql_error(&my_connection));
}
exit(EXIT_SUCCESS);
}
說明:mysql_real_connect其中一個參數”i don't know‘對應不正確的密碼,所以串連失敗。

輸出:connection failed
connection error 1045:Access denied for user
'rick'@'localhost' (using password: YES)

 

編譯指令:gcc 源檔案名稱 -I/usr/include/mysql -L/sur/lib/mysql -lmysqlclient -o 目的檔案名稱

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.