我的照片
姓名:
位置: 北京, China

2010年11月14日 星期日

MySQL和C编程

tom@debian:~$ apt-get install mysql-server libmysqlclient15-dev
tom@debian:~$ mysql -u root -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 42
Server version: 5.0.51a-24+lenny4 (Debian)

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

mysql> create databases test;
mysql> grant all on test to test identified by 'test';
mysql> exit;
Bye

CREATE TABLE `test`.`user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) NOT NULL,
`age` int NOT NULL,
PRIMARY KEY (`id`)
)
ENGINE = InnoDB;

mysql.c
#include <stdio.h>
#include <stdlib.h>
#include "mysql.h"

int main(void) {
MYSQL *connection;
int res;

/*
* MYSQL *mysql_init(MYSQL *);
*/
connection = mysql_init(NULL);
if (!connection) {
fprintf(stderr, "mysql_init failed\n");
exit(EXIT_FAILURE);
}
/*
* MYSQL *mysql_real_connect(MYSQL *connection,
* const char *server_hsot,
* const char *sql_user_name,
* const char *sql_password,
* const char *db_name,
* unsigned int port_number,
* const char *unix_socket_name,
* unsigned int flags);
*/
connection = mysql_real_connect(connection, "localhost", "test", "test", "test", 0, NULL, 0);

if (connection) {
printf("connect success\n");
/*
* int mysql_query(MYSQL *connection,
* const char *query);
*/
res = mysql_query(connection, "INSERT INTO user(name, age) VALUES('Ada', 3)");
if (!res) {
/*
* my_ulonglong mysql_affected_rows(MYSQL *connection);
*/
printf("Insert %lu rows\n", (unsigned long) mysql_affected_rows(connection));
} else {
/*
* unsigned int mysql_errno(MYSQL *connection);
* char *mysql_error(MYSQL *connection);
*/
fprintf(stderr, "Insert error %d: %s\n", mysql_errno(connection), mysql_error(connection));
}
} else {
printf("connect failed\n");
}

/*
* void mysql_close(MYSQL *connection);
*/
mysql_close(connection);

return EXIT_SUCCESS;
}

tom@debian:~/workspace/mysql/src$ gcc -I/usr/include/mysql -L/usr/lib/mysql -lmysqlclient mysql.c -o mysql
tom@debian:~/workspace/mysql/src$ ll
总计 16
-rwxr-xr-x 1 tom tom 8289 11-14 23:00 mysql
-rw-r--r-- 1 tom tom 1666 11-14 22:58 mysql.c
tom@debian:~/workspace/mysql/src$ ./mysql
connect success
Insert 1 rows
tom@debian:~/workspace/mysql/src$

标签:

0 条评论:

发表评论

订阅 帖子评论 [Atom]

<< 主页