VastbaseG100

基于openGauss内核开发的企业级关系型数据库。

Menu

附录2:调用示例

#include "stdafx.h"
#include <string>
#include <iostream>
#include <soci/soci.h>
#include <soci/postgresql/soci-postgresql.h>

using namespace soci;
using namespace std;

int main(){
	session sql;
	try{
		sql.open(postgresql, "dbname=postgres user=vastbase_remote password=Aa@123456 host=172.16.12.234");
	cout << "connect successful!" << endl;
		
//删除表
	sql << "drop table if exists tb_test";
    
//创建表
	sql << "create table tb_test(id integer not null primary key, name text)";
	cout << "create table successful!" << endl;

//插入数据
	sql << "insert into tb_test values (1, 'Anna')";
	sql << "insert into tb_test values (:id, :name)", use(2), use((string)"Jack");
	cout << "insert successful!" << endl;
	
//查询数据
	rowset<row> rs = (sql.prepare << "select * from tb_test");
		
	for(rowset<row>::iterator it = rs.begin();it != rs.end();it++){
		const row& r = *it;
		cout << "id : " << r.get<int>(0)
			 << " name : " << r.get<string>(1)
			 << endl;
		}
		
//rollback
	transaction tr(sql);
	sql << "insert into tb_test values (3, 'Mike')";
	tr.rollback();

	rs = (sql.prepare << "select * from tb_test");
	for(rowset<row>::iterator it = rs.begin();it != rs.end();it++){
		const row& r = *it;
		cout << "after rollback: id : " << r.get<int>(0)
			<< " name : " << r.get<string>(1)
			<< endl;
		}
		
//更新数据
	sql << "update tb_test set name = :name where id = 1",use((string)"Elsa");
	cout << "update successful!" << endl;
	rs = (sql.prepare << "select * from tb_test");
	for(rowset<row>::iterator it = rs.begin();it != rs.end();it++){
		const row& r = *it;
		cout << "after update: id : " << r.get<int>(0)
			 << " name : " << r.get<string>(1)
			 << endl;
		}
		
//删除数据
	sql << "delete from tb_test where id = 1";
	rs = (sql.prepare << "select * from tb_test");
	for(rowset<row>::iterator it = rs.begin();it != rs.end();it++){
		const row& r = *it;
		cout << "after delete: id : " << r.get<int>(0)
			 << " name : " << r.get<string>(1)
			 << endl;
		}
	}
	catch (postgresql_soci_error const & e)
	{
		cerr << "PostgreSQL error: " << e.sqlstate() << " " << e.what() << endl;
	}
	catch (exception const & e)
	{
		cerr << "Some other error: " << e.what() << endl;
	}

	sql.close();

	return 0;
		}