安装
sudo apt-get install mysql-server mysql-client
c语言开发包
sudo apt-get install libmysqlclient15-dev
启动
mysql -u root --password=root
创建测试数据
CREATE DATABASE foo;
use foo;
CREATE TABLE children(
childno int(11) NOT NULL auto_increment,
fname varchar(30),
age int(11),
PRIMARY KEY (childno)
);
INSERT INTO children(childno,fname,age) VALUES(1,'Jenny',21);
INSERT INTO children(childno,fname,age) VALUES(2,'Andrew',17);
INSERT INTO children(childno,fname,age) VALUES(3,'Gavin',8);
INSERT INTO children(childno,fname,age) VALUES(4,'Duncan',6);
INSERT INTO children(childno,fname,age) VALUES(5,'Emma',4);
INSERT INTO children(childno,fname,age) VALUES(6,'Alex',15);
INSERT INTO children(childno,fname,age) VALUES(7,'Adrian',9);
命令行 gedit connect.c
注意帐号和密码
<span style="font-size:18px;">#include <stdlib.h> #include <stdio.h> #include "mysql.h" int main(int argc,char *argv[]) { MYSQL *conn_ptr; conn_ptr = mysql_init(NULL); if(!conn_ptr) { fprintf(stderr,"mysql_init failed\n"); return EXIT_FAILURE; } conn_ptr = mysql_real_connect(conn_ptr,"localhost","root","root","foo",0,NULL,0); if(conn_ptr) printf("Connection success\n"); else printf("Connection failed\n"); mysql_close(conn_ptr); return EXIT_SUCCESS; }</span>
编译
gcc -I/usr/include/mysql connect.c -L/usr/lib/mysql/ -lmysqlclient -o connect
运行
./connect
输出
Connection success
参考文章:http://blog.csdn.net/xiajun07061225/article/details/8505987