环境:fedora16
1)安装:# yum install mysql mysql-devel //mysql-devel同样需要安装,开发中要用到/usr/include/mysql
查看mysql是否启动: service mysqld status ,如果未启动,启动mysql:service mysqld start
详情请查看:http://www.if-not-true-then-false.com/2010/install-mysql-on-fedora-centos-red-hat-rhel/
2)创建数据表
进入mysql:mysql -u root -p 回车,初始密码未空,再次回车
use test
以下为导出数据:创建数据表,插入数据应该可以自己解决吧
--
-- Database: `test`
--
-- --------------------------------------------------------
--
-- Table structure for table `users`
--
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(30) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=4 ;
--
-- Dumping data for table `users`
--
INSERT INTO `users` (`id`, `name`) VALUES
(1, 'tom'),
(2, 'jack'),
(3, 'haha');
3)
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <mysql.h> int main(int argc, char* argv[]) { MYSQL mysql; //连接mysql if (connect_mysql(&mysql)) { return 1; } //载入数据 if (load_users(&mysql)) { mysql_close(&mysql); return 1; } //Do something here. //关闭mysql mysql_close(&mysql); return 0; } //连接MYSQL数据库 int connect_mysql(MYSQL* mysql) { printf("Initializing mysql................."); if (!mysql_init(mysql)) { return 1; } printf("Done\r\n"); printf("Connectiong to mysql..............."); if (!mysql_real_connect(mysql, "localhost", "root", "", "test", 0, NULL,0)) { fprintf(stderr, "Error: %s\r\n", mysql_error(mysql)); return 1; } //设置mysql连接的字符集 mysql_query(mysql, "SET NAMES 'utf8'"); printf("Done\r\n"); return 0; } //加载数据表 int load_users(MYSQL *mysql) { int ret, field_count, row_count, i; int *lengths; char *query = "select * from users"; MYSQL_RES *result; MYSQL_ROW row; ret = mysql_real_query(mysql, query, strlen(query)); if (ret != 0) { printf("加载不了users的数据。\n"); return 1; } result = mysql_store_result(mysql); row_count = (int) mysql_num_rows(result); field_count = (int) mysql_num_fields(result); if (result == NULL && field_count == 0) { printf("无数据"); return 1; } for (i = 0; i < row_count; i++) { row = mysql_fetch_row(result); printf("%s %s\n", row[0], row[1]); } mysql_free_result(result); return 0; }
4)编译:gcc -o bin_name hello.c -I /usr/include/mysql -L /usr/lib/mysql -lmysqlclient -lz -lm
5)执行:(ls一下你发现目录下多了一个bin_name)
./bin_name
祝你成功!~
参考:http://c.chinaitlab.com/database/850508_2.html