MySQLConnectorC++⼊门教程(上)
翻译: DarkBull(www.darkbull)
⽰例代码:
译者注:该教程是⼀篇介绍如何使⽤C++操作MySQL的⼊门教程,内容简单易⽤。我对原⽂中的⼀些例⼦进⾏了修改,并新添加了部分例⼦,主要⽬标是更简单明了的向读者介绍如何操作MySQL数据库。本⼈也是MySQL的初学者,错误也在所难免,欢迎拍砖!
这篇教程将⼀步⼀步引导您如何去构建和安装MySql Connection/C++ Driver,同时提供⼏个简单的例⼦来演⽰如何连接MySQL数据库,如何向MySQL添加、获取数据。本教程关注如何在C++应⽤程序中操作MySQL,所以⾸先应该确定MySQL数据库服务已经开启并且在当前机器能够访问到。
本教程⾯向的读者是MySQL Connector/C++的初学者,如果您对C++语⾔或者MySQL数据库不是很了解,请参考其他的教程。
教程使⽤了下⾯所列的⼀些⼯具和技术,来构建、编译、运⾏例⼦程序(译者注:这是原⽂作者使⽤的环境。笔者使⽤的环境是:WinXP,MySQL5.1,VS2008, ):
Database MySQL Server 5.1.24-rc
C++ Driver MySQL Connector/C++ 1.0.5
MySQL Client Library MySQL Connector/C 6.0
Compiler Sun Studio 12 C++ compiler
Make CMake 2.6.3
Operating System OpenSolaris 2008.11 32-bit
CPU / ISA Intel Centrino / x86
Hardware Toshiba Tecra M2 Laptop
⽬录
MySQL C++ Driver的实现基于JDBC4.0规范
安装MySQL Connector/C++
运⾏时依赖
C++ IDE
为⽰例程序创建数据库与数据表
使⽤Connector/C++测试数据库连接
使⽤prepared Statements
使⽤事务
访问Result Set Metadata
访问Database Metadata
通过PreparedStatment对象访问参数元数据
捕获异常
调试/跟踪 MySQL Connector/C++
更多信息
MySQL C++ Driver的实现基于JDBC4.0规范
MySQL Connector/C++是由Sun Microsystems开发的MySQL连接器。它提供了基于OO的编程接⼝与数据库驱动来操作MySQL服务器。
与许多其他现存的C++接⼝实现不同,Connector/C++遵循了JDBC规范。也就是说,Connector/C++ Driver的API主要是基于Java语⾔的JDBC接⼝。JDBC是java语⾔与各种数据库连接的标准⼯业接⼝。Connector/C++实现了⼤部分JDBC4.0规范。如果C++程序的开发者很熟悉JDBC编程,将很快的⼊门。
MySQL Connector/C++实现了下⾯这些类:
Driver
Connection
Statement
PreparedStatement
ResultSet
Savepoint
DatabaseMetaData
ResultSetMetaData
ParameterMetaData
Connector/C++可⽤于连接MySQL5.1及其以后版本。
在MySQL Connector/C++发布之前,C++程序员可以使⽤MySQL C API或者MySQL++访问MySQL。前者是⾮标准、过程化的C API,后者是对MySQL C API的C++封装。
安装MySQL Connector/C++
此处略。(译者注:⽤户可以到MySQL的官⽹[sql/downloads/connector/cpp/1.0.html]去下载MySQL Connector/C++的安装程序,或者只下载dll,或者下载源代码⾃⼰编译。笔者在Window平台上使⽤MySQL,下载了mysql-connector-c++-noinstall-1.0.5-win32这个版本⽤于调试。)
运⾏时依赖
MySQL Connector/C++ Driver依赖MySQL的客户端库,在MySQL安装⽬录下的lib\opt\libmysql.dll。如果是通过安装程序来安装MySQL Connector/C++,libmysql会⼀并安装,如果从官⽹只下载了dll或源码,在使⽤时,程序必须链接到libmysql.dll。
C++ IDE
此处略。(译者注:原⽂作者使⽤NetBean作为C++的IED。笔者使⽤VS2008)
为⽰例程序创建数据库与数据表
(译者注:此节略掉许多不太重要的内容。)在MySQL中创建test数据库,使⽤下⾯语句创建数据表:City:
Create Table: CREATE TABLE `City` ( `CityName` varchar(30) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=ascii
然后向City表中添加⼀些数据。最后表的内容为:
mysql>SELECT * FROM City;
+--------------------+
| CityName |
+--------------------+
| Hyderabad, India |
| San Francisco, USA|
| Sydney, Australia |mysql下载完如何使用
+--------------------+
3 rows in set (0.17 sec)
使⽤Connector/C++测试数据库连接
下⾯的代码演⽰如何使⽤Connector/C++连接到MySQL服务器:
连接到test数据库;
执⾏⼀个查询获取City表中的数据,显⽰在控制台上;
使⽤Prepared Statements向City表插⼊数据;
使⽤savepoints演⽰事务;
获取结果集和数据库的元信息;
例⼦代码仅仅⽤于演⽰,不建议读者在实际开发中使⽤这种样式的代码。(译者注:例⼦代码很长,如果看不太明⽩,没关系,等阅读完全⽂之后再回过头来看)
#include <iostream>
#include <map>
#include <string>
#include <memory>
#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/metadata.h"
#include "cppconn/exception.h"
#define DBHOST "tcp://127.0.0.1:3306"
#define USER "root"
#define PASSWORD "000000"
#define DATABASE "test"
#define NUMOFFSET 100
#define COLNAME 200
using namespace std;
using namespace sql;
#pragma comment(lib, "mysqlcppconn.lib")
void Demo();
int main(int argc, char *argv[])
{
Demo();
return 0;
}
/* 获取数据库信息 */
static void GetDBMetaData(Connection *dbcon)
{
if (dbcon->isClosed())
{
throw runtime_error("DatabaseMetaData FAILURE - database connection closed");
}
cout << "\nDatabase Metadata" << endl;
cout << "-----------------" << endl;
cout << boolalpha;
/* The following commented statement won't work with Connector/C++ 1.0.5 and later */
//auto_ptr < DatabaseMetaData > dbcon_meta (dbcon->getMetaData());
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;
cout << "\nDatabase schemas: " << endl;
auto_ptr < ResultSet > rs ( dbcon_meta->getSchemas());
cout << "\nTotal number of schemas = " << rs->rowsCount() << endl;
cout << endl;
int row = 1;
while (rs->next()) {
cout << "\t" << row << ". " << rs->getString("TABLE_SCHEM") << endl;
++row;
} // while
cout << endl << endl;
}
/* 获取结果集信息 */
static void GetResultDataMetaBata(ResultSet *rs)
{
if (rs -> rowsCount() == 0)
{
throw runtime_error("ResultSetMetaData FAILURE - no records in the result set");
}
cout << "ResultSet Metadata" << endl;
cout << "------------------" << endl;
/* The following commented statement won't work with Connector/C++ 1.0.5 and later */
//auto_ptr < ResultSetMetaData > res_meta ( rs -> getMetaData() );
ResultSetMetaData *res_meta = rs -> getMetaData();
int numcols = res_meta -> getColumnCount();
cout << "\nNumber of columns in the result set = " << numcols << endl << endl;
cout.width(20);
cout << "Column Name/Label";
cout.width(20);
cout << "Column Type";
cout.width(20);
cout << "Column Size" << endl;
for (int i = 0; i < numcols; ++i)
{
cout.width(20);
cout << res_meta -> getColumnLabel (i+1);
cout.width(20);
cout << res_meta -> getColumnTypeName (i+1);
cout.width(20);
cout << res_meta -> getColumnDisplaySize (i+1) << endl << endl;
}
cout << "\nColumn \"" << res_meta -> getColumnLabel(1);
cout << "\" belongs to the Table: \"" << res_meta -> getTableName(1);
cout << "\" which belongs to the Schema: \"" << res_meta -> getSchemaName(1) << "\"" << endl << endl; }
/* 打印结果集中的数据 */
static void RetrieveDataAndPrint(ResultSet *rs, int type, int colidx, string colname)
{
/* retrieve the row count in the result set */
cout << "\nRetrieved " << rs->rowsCount() << " row(s)." << endl;
cout << "\nRetrieved " << rs->rowsCount() << " row(s)." << endl;
cout << "\nCityName" << endl;
cout << "--------" << endl;
/* fetch the data : retrieve all the rows in the result set */
while (rs->next())
{
if (type == NUMOFFSET)
{
cout << rs -> getString(colidx) << endl;
} else if (type == COLNAME)
{
cout << rs -> getString(colname) << endl;
} // if-else
} // while
cout << endl;
}
void Demo()
{
Driver *driver;
Connection *con;
Statement *stmt;
ResultSet *res;
PreparedStatement *prep_stmt;
Savepoint *savept;
int updatecount = 0;
/* initiate url, user, password and database variables */
string url(DBHOST);
const string user(USER);
const string password(PASSWORD);
const string database(DATABASE);
try
{
driver = get_driver_instance();
/* create a database connection using the Driver */
con = driver -> connect(url, user, password);
/* alternate syntax using auto_ptr to create the db connection */
//auto_ptr con (driver -> connect(url, user, password));
/* turn off the autocommit */
con -> setAutoCommit(0);
cout << "\nDatabase connection\'s autocommit mode = " << con -> getAutoCommit() << endl;
/* select appropriate database schema */
con -> setSchema(database);
/* retrieve and display the database metadata */
GetDBMetaData(con);
/* create a statement object */
stmt = con -> createStatement();
cout << "Executing the Query: \"SELECT * FROM City\" .." << endl;
/* run a query which returns exactly one result set */
res = stmt -> executeQuery ("SELECT * FROM City");
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论