vc操作mysql的典型例子

vc操作mysql的典型例子
1.包含文件

#include "mysql.h"

2.初始化数据库

	//开始链接数据库
	//MYSQL mysql;//定义成全局的
	mysql_init(&mysql);
	mysql_options(&mysql, MYSQL_SET_CHARSET_NAME, "GB2312"); 

	if(!mysql_real_connect(&mysql,"localhost","user","password","user_db",3306,NULL,0))
	{
		AfxMessageBox("数据库连接失败");
	}
	else
	{
		//MessageBox("链接数据库成功!");
	}

3.插入数据

	//添加到数据库
	
	CString strSQL = "insert into xbzq.group values(NULL,'test');";
	const char * q =strSQL;
	mysql_query(&mysql,q);

4.读出数据

	strsql = "select * from sentence_lib where id = " + m_nId;
	mysql_query(&mysql,strsql);
	res = mysql_store_result(&mysql);
	MYSQL_ROW row=NULL;
	row = mysql_fetch_row(res);
	strpassage = strpassage+row[1];



/////////////////////

	//从数据库中随机取出一个句子
	CString strsql="select * from sentence_lib";
	const char * q =strsql;
	mysql_query(&mysql,q);

	MYSQL_RES *res = mysql_store_result(&mysql);

	//mysql_use_result(MYSQL *mysql);

	int nRow = res->row_count;//得到组文章用的句子库的数量
	

Leave a Reply