分类: Mysql/postgreSQL
2011-08-15 20:24:24
/*
* 连接数据库
*/
#include
using namespace mysqlpp;
using namespace std;
int main()
{
Connection con(true);
try{
con.connect("test","localhost","root","123456",3306);
cout<<"数据库连接成功"<<endl;
}catch(ConnectionFailed e){
cout<<"数据库连接失败"<<endl;
cout<<"ConnectionFailed:"<<con.error()<<endl;
}catch(Exception e){
cout<<"Exception:"<<con.error()<<endl;
}
con.disconnect();
return 0;
}
/*
* 数据插入
*/
#include
using namespace mysqlpp;
using namespace std;
int main()
{
Connection con(true);
try{
con.connect("test","localhost","root","123456",3306);
cout<<"数据库连接成功"<<endl;
Query query = con.query("insert into student values(40,'denny',40)");
query.execute();
cout<<"数据库插入成功"<<endl;
}catch(ConnectionFailed e){
cout<<"数据库连接失败"<<endl;
cout<<"ConnectionFailed:"<<con.error()<<endl;
}catch(BadQuery e){
cout<<"数据库操作失败"<<endl;
cout<<"ConnectionFailed:"<<con.error()<<endl;
}catch(Exception e){
cout<<"Exception:"<<con.error()<<endl;
}
con.disconnect();
}
/*
* 查旬数据
*/
#include
using namespace mysqlpp;
using namespace std;
int main()
{
Connection con(true);
try{
con.connect("test","localhost","root","123456",3306);
cout<<"数据库连接成功"<<endl;
Query query = con.query("select * from student");
StoreQueryResult res = query.store();
cout << "We have:" << endl;
for (size_t i = 0; i < res.num_rows(); ++i) {
cout << '\t' << res[i][0]<<' ' <<res[i][1] << endl;
}
cout<<"数据库查询成功"<<endl;
}catch(ConnectionFailed e){
cout<<"数据库连接失败"<<endl;
cout<<"ConnectionFailed:"<<con.error()<<endl;
}catch(BadQuery e){
cout<<"数据库操作失败"<<endl;
cout<<"ConnectionFailed:"<<con.error()<<endl;
}catch(Exception e){
cout<<"Exception:"<<con.error()<<endl;
}
con.disconnect();
}
#include
using namespace mysqlpp;
using namespace std;
int main()
{
Connection con(true);
try{
con.connect("test","localhost","root","123456",3306);
cout<<"数据库连接成功"<<endl;
Query query = con.query("select * from student where name != %0q");
query.parse();
StoreQueryResult res = query.store("denny");
/*
Query query = con.query("select * from student where name != %0q and cid=%1q");
query.parse();
StoreQueryResult res = query.store("denny",10)
*/
cout << "We have:" << endl;
for (size_t i = 0; i < res.num_rows(); ++i) {
cout << '\t' << res[i][0]<<' ' <<res[i][1] << endl;
}
cout<<"数据库查询成功"<<endl;
}catch(ConnectionFailed e){
cout<<"数据库连接失败"<<endl;
cout<<"ConnectionFailed:"<<con.error()<<endl;
}catch(BadQuery e){
cout<<"数据库操作失败"<<endl;
cout<<"ConnectionFailed:"<<con.error()<<endl;
}catch(Exception e){
cout<<"Exception:"<<con.error()<<endl;
}
con.disconnect();
}
编译上面实例需安装好 mysql C 和 Mysql C++ mysql++.rar