c++ 操作mysql

来源:互联网 发布:java程序员面试指南 编辑:程序博客网 时间:2024/06/01 21:16
总结VC环境下C++连接MySQL
一、 环境配置
第一步:工程->设置->连接->对象/库模块,添加libmysql.lib
第二步:工具->选项->目录->路径,加入MySQL的include文件,lib/opt
第三步:在工程所在文件中加入libmysql.dll文件(此文件在MySQL文件的子文件lib/debeg里)
二、头文件的引入
需要引入Winsock2.h和mysql.h(Winsock2.h的作用是:)
三、数据库的连接
1、、mysql_library_init(0,NULL,NULL);//初始化数据库
2、、mysql_init(&mydata);//初始化数据结构
3、、mysql_options(&mydata,MYSQL_SET_CHARSET_NAME,"UTF8");//设置编码方式  
4、、mysql_real_connect(&mydata,"localhost","root","1234","hotel",3306,"NULL",0);//数据库的连接(定义的数据库对象,本地/MySQL的服务端ip,用户名,密码,数据库名,固定,,,)
四、数据库的使用
数据库的使用主要是利用sql语句,这里挑选几个例子说明:
stirng sqlstr ;
1、、查看表中的某行数据sqlstr="select * from tablename(表名) where (字段名)=\'"+string(字符串)+"\'";
每次调用sql语句后,真正要被C++环境知道,就要执行以下语句:
mysql_query(&mydata(数据库的对象),sqlstr.c_str()(这里需要一个));
2、、向表中添加一行数据第一种方法:sprintf(sqlstr, "INSERT INTO room VALUES('%s','%s','%s',%d,'%s')", num,type,capacity,price,state);
第二种方法:sqlstr ="INSERT INTO room VALUES(\'"+num+"\',\'"+type+"\',\'"+capacity+"\',\'"+price+"\',\'"+state+"\');";
3、、获得表中特定行的某个数据:
sqlstr="select * from info(表名) where customername(字段名)=\'"+name(字符串)+"\'; ";
mysql_query(&mydata,sqlstr.c_str());
result=mysql_store_result(&mydata);(MYSQL_RES *result=NULL;)
row=mysql_fetch_row(result);(MYSQL_ROW row=NULL;)
intime=row[2];[把表中获得的数据row【2】(表中第三个数据)复制给intime]
4、、表头和各行的输出:
表头
MYSQL_RES *result=NULL;
result=mysql_store_result(&mydata);//
int rowcount=mysql_num_rows(result);//统计行数
cout<<"row count: "<<rowcount<<endl;

unsigned int fieldcount=mysql_num_fields(result);//统计字段数
MYSQL_FIELD *field=NULL;
for(unsigned int i=0;i<fieldcount;i++)
{
field=mysql_fetch_field_direct(result,i);
cout<<field->name<<"\t\t";//输出字段内容
}
cout<<endl;
各行的输出:
MYSQL_ROW row=NULL;
row=mysql_fetch_row(result);
while(NULL!=row)
{
for(i=0; i<fieldcount;i++)
{
cout<<row[i]<<"\t\t";//输出各行内容(打印一行不再使用循环,只按数组输出特定行)
}
cout<<endl;
row=mysql_fetch_row(result);
}
原创粉丝点击