周末,闲着的时候突然想起来所谓的数据库编程, 但是具体怎么操作确实全然不知。教学上用postresql,公司里估计是没有用处的吧,所以,就拿mysql来做试验了,哈哈
其实,刚开始还是蛮难的,感觉。看网上的例子,就像丈二和尚-----摸不着头脑,突然有种回到了刚开始学习C语言那时候的感觉,什么都不懂,一个简单的编译错误也不想认真看,自己去想,就想找个人问,这个到底是怎么错了?呵呵,所幸,那会没有浮躁。
mysql本身带了很多C API,所以操作起来很方便,直接调用API就好了,不过加入相应的库在刚开始就够难为人了,毕竟,这个是我第一次加入外来库。。
vc6.0添加mysql #include 头文件: 工程->设置->C/C++ Y分类那里选择Preprocessor,然后在附加包含路径里写上:C:\Program Files\MySQL\MySQL Server 5.0\include
就OK 了
在编写程序时添加进去相应的lib库,使用:#pragma comment(lib, "libmysql.lib")
.lib 对应的.dll也要拷贝到工程目录下。
完整的例子如下:
#include <iostream>
#include <windows.h>
#include <cstdlib>
#include <cstdio>
#include <mysql.h>
#pragma comment(lib, "libmysql.lib")
using namespace std;
MYSQL * conn;
int main()
{
char host[] = "localhost";
char username[] = "root";
char password[] = "123";
char database[] = "school";
MYSQL_RES * res_set;
MYSQL_ROW row;
unsigned int i, ret;
MYSQL_FIELD * field;
unsigned int num_fields;
//mysql_init(MYSQL *)
// return values: An initialized MYSQL* handle.
//NULL if there was insufficient memory to allocate a new object.
conn = mysql_init(NULL);
if(conn != NULL)
;//cout << "mysql_init success!" << endl;
else printf("failed !\n");
ret = mysql_options(conn, MYSQL_SET_CHARSET_NAME, "gb2312");//来保证你字码, 要加重记住.没这个设置写到数据mysql里就是乱码了, 汉字就是乱码
if(ret == 0)
;//cout << "mysql_options success!" << endl;
else printf("failed !\n");
if(mysql_real_connect(conn,
host,
username,
password,
database,
0, NULL, 0) != NULL)
;//cout << "mysql_real_connect success!" << endl;
else printf("failed !\n");
//printf("char set %s\n", mysql_character_set_name(conn));
mysql_query(conn, "insert into teacher values(7, 'fifth', '插入汉字', '1986-6-6')"); //这到数据里就不是乱码了.
printf("insert affect %d sentences\n", mysql_affected_rows(conn));
if(mysql_query(conn,"SELECT * FROM teacher")) //查询成功返回0 failed here!
printf("mysql_query failed!\n");
res_set = mysql_store_result(conn); //失败返回NULL
if(res_set == NULL)
printf("res_set is null\n");
/*
while((field = mysql_fetch_field(res_set)))
{
printf("field name %s\n", field->name);
}
*/
num_fields = mysql_num_fields(res_set);
for(i = 0; i < num_fields; i++)
{
field = mysql_fetch_field_direct(res_set, i);
printf("%s\t\t", field->name);
}
printf("\n");
while ((row = mysql_fetch_row(res_set)) != NULL)
{
for (i = 0; i < mysql_num_fields(res_set); i ++)
{
printf("%s\t\t",row[i] != NULL ? row[i] : "NULL");
}
printf("\n");
}
mysql_close(conn);
return 0;
}
函数我就不详细注释了,在mysql的帮助文档里有详细的注释。