mysqlconnectorc教程_MySQLConnectorC++操作MySQL数据
库(例程)
如果我翻译错了或者翻译的不好,欢迎指正~
Developing Database Applications Using MySQL Connector/C++
这个教程会教你搭建安装MySQL Connector/C++ driver的要点和步骤,以⼀个简单的连接MySQL的例⼦,从MySQL中获取数据并对其进⾏插⼊(数据)操作。因为重点在于从C++程序连接数据库,所以本⽂档假设MySQL已经运⾏并且能从客户端访问。
本⽂是⾯向那些初次接触MySQL Connector/C++的程序开发者的教程,并不是讲述C++编程和MySQL数据库的。
构建和运⾏本教程的例⼦需要下列⼯具和技术来编译:
DatabaseMySQL Server 5.1.24-rc
C++ DriverMySQL Connector/C++ 1.0.5
MySQL Client LibraryMySQL Connector/C 6.0
CompilerSun Studio 12 C++ compiler
MakeCMake 2.6.3
Operating SystemOpenSolaris 2008.11 32-bit
CPU / ISAIntel Centrino / x86
HardwareToshiba Tecra M2 Laptop
CONTENTS
MySQL C++ Driver 基于JDBC 4.0标准实现
MySQL Connector/C++是最新发布的MySQL连接器,由Sun Microsystems开发。MySQL connector为C++提供⾯向对象的编程接⼝(API)和连接MySQL Server的数据库驱动器
与现存的driver不同,Connector/C++是JDBC API在C++中的实现。换句话说,Connector/C++ driver的接⼝主要是基于Java语⾔的JDBC API。Java数据库连接(JDBC)是Java连接各种数据库的业界标准。
Connector/C++实现了JDBC 4.0的⼤部分规范。熟悉JDBC编程的C++程序开发者可以提⾼程序开发的效率。
MySQL Connecotr/C++实现了以下类:
Driver
Connection
Statement
PreparedStatement
ResultSet
Savepoint
DatabaseMetaData
ResultSetMetaData
ParameterMetaData
Connecotr/C++ driver可⽤于连接MySQL5.1以及后续版本。
在MySQL Connector/C++出现之前,C++程序员需要使⽤⾮标准的、过程化的MySQL C API或MySQL++ API连接MySQL,MySQL Connector/C++是MySQL C API的C++封装
安装MySQL Connector/C++
从⼆进制程序安装
从1.0.4版本开始,Connector/C++可⽤于Solaris, Linux, Windows, FreeBSD, Mac OS X, HP-UX and AIX平台。MSI安装程序和⼆进制ZIP⽂件并不需要安装程序可⽤于Windows,GNU TAR的压缩⽂档()可⽤于其他的平台。你可以从“Connector/C++ download“下载预编译的⼆进制⽂件。
在Windows和其他平台下⼆进制包的安装是⾮常简单的-简单的解压缩⽂档到指定位置安装Connector/C++ driver。静态链接和动态链接的Connector/C++ driver可以在安装⽬录下到lib⽬录。如果您打算使⽤动态链接版本的MySQL连接器/ C + +,要确保运⾏时链接程序可以到MySQL客户端库。请查阅你操作系统⽂档,修改和扩展库的搜索路径。如果你⽆法修改库的搜索路径,那么复制你的程序、MySQL Connector/C++ driver和MySQL客户端库到相同的⽬录。这种⽅法在⼤多数平台都可⾏,编译器到其他地⽅都所必须动态库之前会先搜索原始⽬录(当前⽬录)。
从源码安装
运⾏时依赖
略(英语⽔平有限,这⼀段翻译的不通畅,就不写了,于阅读本教程没什么影响)
使⽤IDE开发C++程序
如果你正在寻⼀个集成开发环境(IDE)来开发C/C++程序,可以考虑使⽤开源免费的NetBeans平台。NetBeans C/C++开发包让程序员可以使⽤他们指定的编译器和⼯具来搭配NetBeans IDE,构建Solaris,Linux,Windows和Mac OS X的原⽣应⽤。C/C++开发包使编辑器具有语⾔识别功能,可以识别C/C++语⾔,并且提供项⽬模板,⼀个动态类浏览器,⽀持Makefile和m(不知道是什么)调试器功能。可以通过模块和插件来扩展C/C++开发包的基础功能。
为实例代码创建City表和test数据库
本教程中的简单⽰例代码尝试获取MySQL中的test数据库中的City表的数据。此表的结构和数据已经使⽤mysql客户端显⽰在下⾯。MySQL服务运⾏在3306默认端⼝。
# mysql -u root -p
Enter password: admin
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 5
Server version: 5.1.24-rc-standard Source distribution
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
mysql> USE test;
Database changed
mysql> DESCRIBE City;
+----------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| CityName | varchar(30) | YES | | NULL | |
+----------+-------------+------+-----+---------+-------+
1 row in set (0.07 sec)
mysql> SHOW CREATE TABLE City\G
*************************** 1. row ***************************
Table: City
Create Table: CREATE TABLE `City` (
`CityName` varchar(30) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=ascii
1 row in set (0.00 sec)
mysql> SELECT * FROM City;
+--------------------+
| CityName |
+--------------------+
| Hyderabad, India |
| San Francisco, USA |
| Sydney, Australia |
+--------------------+
3 rows in set (0.17 sec)
本教程的所有例⼦的运⾏结果都是使⽤bash shell显⽰
使⽤Connector/C++测试与数据库连接
下⾯的C++⽰例代码简单演⽰如何使⽤MySQL Connector/C++连接本机的MySQL服务。实例代码使⽤
Connector/C++提供的类似于JDBC的API连接到MySQL中的test数据库,实⾏⼀条查询语句,从City表中获取所有⾏数据,从结果集中提取数据并显⽰在标准输出上,使⽤"Prepared Statements"插⼊⼏⾏数据到City表中。
⽰例代码仅仅供参考。不建议读者使⽤特定的编码风格。为了简单起见,实例代码假设⽤户提供了合法的输⼊,所以下⾯例⼦中并没有明确的错误检测代码。
# cat MySQLConnectorC++Client.cpp/*Standard C++ headers*/#include#include#include#include#include
/*MySQL Connector/C++ specific headers (注意:所有头⽂件都放在/usr/include/cppconn/下
⾯)*/#include#include#include#include#include#include#include#include#include
#define DBHOST "tcp://127.0.0.1:3306"
#define USER "root"
#define PASSWORD "admin"
#define DATABASE "test"
#define NUMOFFSET 100
#define COLNAME 200
using namespacestd;using namespacesql;static void retrieve_data_and_print (ResultSet *rs, int type, int colidx, stringcolname) {/*retrieve the row count in the result set*/cout<< "\nRetrieved" << rs -> rowsCount() << "row(s)." <
cout<< "\nCityName" <
cout<< "--------" <
while (rs->next()) {if (type ==NUMOFFSET) {
cout<< rs -> getString(colidx) <
}else if (type ==COLNAME) {
cout<< rs -> getString(colname) <
}//if-else
} //while
cout<
}//retrieve_data_and_print()
static void retrieve_dbmetadata_and_print (Connection *dbcon) {if (dbcon ->isClosed()) {throw
runtime_error("DatabaseMetaData FAILURE - database connection closed");
}
cout<< "\nDatabase Metadata" <
cout<< "-----------------" <
cout<
//auto_ptr < DatabaseMetaData > dbcon_meta (dbcon -> getMetaData());
DatabaseMetaData*dbcon_meta = dbcon ->getMetaData();
cout<< "Database Product Name:" << dbcon_meta -> getDatabaseProductName() <
cout<< "Database Product Version:" << dbcon_meta -> getDatabaseProductVersion() <mysql下载后的初次使用
cout<< "Database User Name:" << dbcon_meta -> getUserName() << endl <
cout<< "Driver name:" << dbcon_meta -> getDriverName() <
cout<< "Driver version:" << dbcon_meta -> getDriverVersion() << endl <
cout<< "Database in Read-Only Mode?:" << dbcon_meta -> isReadOnly() <
cout<< "Supports Transactions?:" << dbcon_meta -> supportsTransactions() <
cout<< "Supports DML Transactions only?:" << dbcon_meta -> supportsDataManipulationTransactionsOnly() < cout<< "Supports Batch Updates?:" << dbcon_meta -> supportsBatchUpdates() <
cout<< "Supports Outer Joins?:" << dbcon_meta -> supportsOuterJoins() <
cout<< "Supports Multiple Transactions?:" << dbcon_meta -> supportsMultipleTransactions() <
cout<< "Supports Named Parameters?:" << dbcon_meta -> supportsNamedParameters() <
cout<< "Supports Statement Pooling?:" << dbcon_meta -> supportsStatementPooling() <
cout<< "Supports Stored Procedures?:" << dbcon_meta -> supportsStoredProcedures() <
cout<< "Supports Union?:" << dbcon_meta -> supportsUnion() << endl <
cout<< "Maximum Connections:" << dbcon_meta -> getMaxConnections() <
cout<< "Maximum Columns per Table:" << dbcon_meta -> getMaxColumnsInTable() <
cout<< "Maximum Columns per Index:" << dbcon_meta -> getMaxColumnsInIndex() <
cout<< "Maximum Row Size per Table:" << dbcon_meta -> getMaxRowSize() << "bytes" <
cout<< "\nDatabase schemas:" <
auto_ptr< ResultSet > rs ( dbcon_meta ->getSchemas());
cout<< "\nTotal number of schemas =" << rs -> rowsCount() <
cout<next()) {
cout<< "\t" << row << "." << rs -> getString("TABLE_SCHEM") <
}//while
cout<< endl <
}//retrieve_dbmetadata_and_print()
static void retrieve_rsmetadata_and_print (ResultSet *rs) {if (rs -> rowsCount() == 0) {throw runtime_error("ResultSetMetaData FAILURE - no records in the result set");
}
cout<< "ResultSet Metadata" <
cout<< "------------------" <
//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 <
cout.width(20);
cout<< "Column Name/Label";
cout.width(20);
cout<< "Column Type";
cout.width(20);
cout<< "Column Size" <
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 <
}
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 <
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论