赞
踩
mysql_init API文档链接别点了,也没样例代码,反正我是看不懂。
要使用库,必须先进行初始化!
函数:
MYSQL *mysql_init(MYSQL *mysql);
样例:
初始化完毕之后,必须先链接数据库,进行后续操作。(mysql网络部分是基于TCP/IP的)
函数:
MYSQL *mysql_real_connect(MYSQL *mysql, const char *host, const char *user,
const char *passwd,const char *db, unsigned int port,
const char *unix_socket, unsigned long client_flag);
函数:
int mysql_set_character_set(MYSQL *mysql, const char *csname)
函数:
int mysql_select_db(MYSQL *mysql, const char *db)
函数:
int mysql_query(MYSQL *mysql, const char *stmt_str)
函数:
MYSQL_RES *mysql_store_result(MYSQL *mysql)
函数:
uint64_t mysql_num_rows(MYSQL_RES *result);
unsigned int mysql_num_fields(MYSQL_RES *result)
函数:
MYSQL_ROW mysql_fetch_row(MYSQL_RES *result)
函数:
void mysql_free_result(MYSQL_RES *result)
函数:
void mysql_close(MYSQL *mysql)
函数:
const char *mysql_error(MYSQL *mysql)
库名:test_db
表名:test_tb{
id(int)
age(int)
name(varcher32)
score(decimal(4,2))
}
create database if not exists test_db;
use test_db;
create table if not exists test_tb(
id int primary key auto_increment,
age int,
name varchar(32),
score decimal(4, 2)
);
#include<iostream> #include<mysql/mysql.h> #include<string> using namespace std; int main() { //1.操作句柄初始化,参数为空就动态申请句柄进行初始化 MYSQL* mysql = mysql_init(NULL); if(mysql==NULL) { cerr<<"init mysql handle failed"<<endl; return -1; } string host = "127.0.0.1"; string user = "root"; string passwd ="123456789.whC"; string dp = "test_db"; //2.链接数据库 if( mysql_real_connect(mysql,host.c_str(),user.c_str(),passwd.c_str(),dp.c_str(),0,NULL,0)==NULL) { cerr<<"mysql connect error "<<mysql_error(mysql)<<endl; return -1; } //3.设置字符集 mysql_set_character_set(mysql,"utf8"); //4.选择数据库 int ret = mysql_select_db(mysql,"test_db"); if(ret!=0) { cerr<<"select db error"<<endl; } //增 // string sql = "insert into test_tb (age,name,score)values(18,'whc',12.33);"; // ret = mysql_query(mysql,sql.c_str()); // if(ret!=0) // { // cerr<<"mysql query select error"<<endl; // } //改 string sql1 ="update test_tb set age=100 where id=2;"; ret = mysql_query(mysql,sql1.c_str()); if(ret!=0) { cerr<<"mysql query update error"<<endl; } string sql2 ="delete from test_tb where id =6;"; //删 // mysql_query(mysql,sql2.c_str()); //查 string sql3 ="select * from test_tb;"; //执行语句 ret = mysql_query(mysql,sql3.c_str()); if(ret!=0) { cerr<<"mysql query select error"<<endl; return -1; } //保存查询结果到本地 MYSQL_RES* result = mysql_store_result(mysql); //获取结果集中的行数 uint64_t row_nums = mysql_num_rows(result); //获取结果集中的列数 unsigned int field_nums = mysql_num_fields(result); cout<<row_nums<<" "<<field_nums<<endl; //遍历结果集 MYSQL_ROW row; for(int i = 0;i<row_nums;i++) { row = mysql_fetch_row(result); for(int j = 0;j<field_nums;j++) { cout<<row[j]<<" "; } cout<<endl; } //释放结果集 mysql_free_result(result); //关闭数据库客户端连接,销毁句柄 mysql_close(mysql); return 0; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。