Ubuntu下用C直接操作Mysql資料庫的方法

來源:互聯網
上載者:User
ubuntu下用C直接操作Mysql資料庫的方法

轉載自:http://hi.baidu.com/wdr_cloud/item/7d87e609102b24943d42e251

以下內容僅供個人學習之用,切勿挪用他途。

首先安裝好mysql,一般情況下是沒有mysql.h這個標頭檔的。

sudo apt-get install mysql-server mysql-client
sudo apt-get install libmysqlclient15-dev

安裝好後,用find尋找mysql.h的路徑

example:/usr/include/mysql/mysql.h(我的是在這個路徑下)

1,使用c語言操作mysql之前,先在mysql裡頭建立一個資料庫,一個表,在表裡頭添加資料如下:
      

建立資料庫,庫名為wang:
mysql>create database wang;
建立表,表名為:
mysql>use wang;
mysql>create table stu(sno int,fname varchar(20),age int);

添加資料:

insert into stu values(1,"dingding",24);

insert into stu values(2,"wang",22);

2 ,下面進行具體的操作

插入:insert.c

#i nclude <stdio.h>
#i nclude <stdlib.h>
#i nclude "/usr/include/mysql/mysql.h" 

int main(int argc, char *argv[])
{
MYSQL my_connection;

int res;

mysql_init(&my_connection);

if (mysql_real_connect(&my_connection, "localhost", "root", "","wang",0,NULL,CLIENT_FOUND_ROWS))

{
    printf("Connection success\n");
    res = mysql_query(&my_connection, "insert into stu values(3,'apple',21)");

    if (!res)
    {
        printf("Inserted %lu rows\n",(unsigned long)mysql_affected_rows(&my_connection));
    }
    else
    {
        fprintf(stderr, "Insert error %d: %s\n",mysql_errno(&my_connection),mysql_error(&my_connection));
    }
    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));
        }
}
    return EXIT_SUCCESS;
}

 

編譯:

gcc -o insert insert.c -l mysqlclient

./insert

Connection Success
Inserted 1 rows

更新:update

我們只要把上面的代碼中的

res = mysql_query(&my_connection, "insert into stu values(3,'apple',21)");

換成

res = mysql_query(&my_connection, "update stu set age=19 where sno>2 ");

即可

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.