C++连接msyql数据库-静态编译(mysql-connector-c++)

// MysqlDemo.cpp : 定义控制台应用程序的入口点。  
// 静态库必须跟vs版本相匹配,不然报错(LNK2038 检测到“_MSC_VER”的不匹配项: 值“1800”不匹配值“1900”)
// 包含文件:mysql-connector-c++的include与boost的根目录
// lib包含:mysqlcppconn-static.lib
#include "stdafx.h"
#include <iostream>
#include <map>
#include <vector>
#include <string>
#include <memory>
#include <algorithm>

// 表示是静态编译
#ifndef _DEBUG
	#define CPPCONN_LIB_BUILD
#endif

#include "mysql_driver.h"
#include "mysql_connection.h"
#include "cppconn/driver.h"
#include "cppconn/statement.h"
#include "cppconn/prepared_statement.h"
#include "cppconn/metadata.h"
#include "cppconn/exception.h"

#define DBHOST "tcp://127.0.0.1:3306"
#define USER "root"
#define PASSWORD ""
#define DATABASE "mydb"

using namespace std;
using namespace sql;

#pragma comment(lib, "mysqlcppconn-static.lib")    

static void GetDBMetaData(Connection *dbcon);
vector<map<string, string>> getQueryResult(Statement *stmt, const string &sql);

int main(int argc, char *argv[])
{
	Driver *driver;
	Connection *con;
	Statement *stmt;
	PreparedStatement *prep_stmt;
	Savepoint *savept;
	int updatecount = 0;
	try
	{
		// 获取数据库驱动  
		driver = get_driver_instance();
		// 连接数据库  
		con = driver->connect(DBHOST, USER, PASSWORD);
		// 关闭自动提交  
		con->setAutoCommit(0);
		cout << "当前数据库提交模式:" << con->getAutoCommit() << endl;
		// 选择数据库  
		con->setSchema(DATABASE);
		// 打印当前数据库的基本信息  
		GetDBMetaData(con);
		// 从连接池中获取一个数据库的映射实例  
		stmt = con->createStatement();
		auto res = getQueryResult(stmt, "SELECT username,password FROM user ORDER BY id ASC LIMIT 10");
		// 打印第一条数据的用户名和密码
		cout << res[0]["username"] << "--" << res[0]["password"] << endl;
		// 向表中插入数据  
		prep_stmt = con->prepareStatement("INSERT INTO user (username,password,addtime) VALUES (?,?,?)");
		prep_stmt->setString(1, "liujun");
		prep_stmt->setString(2, "56464");
		prep_stmt->setString(3, "20132563");
		// 执行更新操作
		updatecount = prep_stmt->executeUpdate();
		// 设置一个事务断点
		savept = con->setSavepoint("SAVEPT1");
		// 执行更新操作,此操作在事务SAVEPT1中
		prep_stmt->setString(1, "sdfsdfsd");
		prep_stmt->setString(2, "12641561");
		prep_stmt->setString(3, "1611561565");
		updatecount = prep_stmt->executeUpdate();
		// 回滚事务SAVEPT1
		con->rollback(savept);
		// 释放此事务断点
		con->releaseSavepoint(savept);
		// 将此前的所有操作一次性提交
		con->commit();
		// 删除堆中的指针
		delete stmt;
		delete savept;
		delete prep_stmt;
		// 关闭数据库连接,并清除该指针
		con->close();
		delete con;
	}
	catch (SQLException &e) {
		cout << "ERROR: " << e.what() << " (MySQL error code: "
			<< e.getErrorCode() << ", SQLState: " << e.getSQLState() << ")" << endl;

		if (e.getErrorCode() == 1047) {
			cout << "您的数据库版本可能过低. " << endl;
		}
	}
	catch (std::runtime_error &e) {
		cout << "ERROR: " << e.what() << endl;
	}
	getchar();
	return 0;
}


/* 封装查询语句*/
vector<map<string, string>> getQueryResult(Statement *stmt, const string &sql) {
	// 获取查询结果
	ResultSet *pres = stmt->executeQuery(sql);
	ResultSetMetaData *pres_meta = pres->getMetaData();
	// 声明返回值
	vector<map<string, string>> retArray;
	// 查询的字段总数
	int field_num = pres_meta->getColumnCount();
	map<string, string> col;
	while (pres->next())
	{
		for (int i = 0; i < field_num; ++i)
			col.insert(make_pair(pres_meta->getColumnLabel(i + 1), pres->getString(i + 1)));
		retArray.push_back(col);
		col.clear();
	}
	delete pres;
	return retArray;

}
/* 获取数据库信息 */
static void GetDBMetaData(Connection *dbcon)
{
	if (dbcon->isClosed())
		throw runtime_error("DatabaseMetaData FAILURE - database connection closed");
	cout << "Database Metadata" << endl;
	cout << "-----------------" << endl;
	// 查询数据库基本信息
	DatabaseMetaData *dbcon_meta = dbcon->getMetaData();
	cout << "Database Product Name: " << dbcon_meta->getDatabaseProductName() << endl;
	cout << "Database Product Version: " << dbcon_meta->getDatabaseProductVersion() << endl;
	cout << "Database User Name: " << dbcon_meta->getUserName() << endl << endl;
	cout << "Driver name: " << dbcon_meta->getDriverName() << endl;
	cout << "Driver version: " << dbcon_meta->getDriverVersion() << endl << endl;
	cout << "Database in Read-Only Mode?: " << dbcon_meta->isReadOnly() << endl;
	cout << "Supports Transactions?: " << dbcon_meta->supportsTransactions() << endl;
	cout << "Supports DML Transactions only?: " << dbcon_meta->supportsDataManipulationTransactionsOnly() << endl;
	cout << "Supports Batch Updates?: " << dbcon_meta->supportsBatchUpdates() << endl;
	cout << "Supports Outer Joins?: " << dbcon_meta->supportsOuterJoins() << endl;
	cout << "Supports Multiple Transactions?: " << dbcon_meta->supportsMultipleTransactions() << endl;
	cout << "Supports Named Parameters?: " << dbcon_meta->supportsNamedParameters() << endl;
	cout << "Supports Statement Pooling?: " << dbcon_meta->supportsStatementPooling() << endl;
	cout << "Supports Stored Procedures?: " << dbcon_meta->supportsStoredProcedures() << endl;
	cout << "Supports Union?: " << dbcon_meta->supportsUnion() << endl << endl;
	cout << "Maximum Connections: " << dbcon_meta->getMaxConnections() << endl;
	cout << "Maximum Columns per Table: " << dbcon_meta->getMaxColumnsInTable() << endl;
	cout << "Maximum Columns per Index: " << dbcon_meta->getMaxColumnsInIndex() << endl;
	cout << "Maximum Row Size per Table: " << dbcon_meta->getMaxRowSize() << " bytes" << endl;

	// 查看数据库中有多少库,以及库名是什么
	shared_ptr < ResultSet > rs(dbcon_meta->getSchemas());
	cout << "Total number of schemas = " << rs->rowsCount() << endl;
	for (int row = 1; rs->next(); ++row)
		cout << row << "=>" << rs->getString("TABLE_SCHEM") << endl;
}


你可能感兴趣的:(C++连接msyql数据库-静态编译(mysql-connector-c++))