Msaada wa Database kwa kutumia SQL...

Msaada wa Database kwa kutumia SQL...

kuku dume

JF-Expert Member
Joined
Apr 22, 2012
Posts
414
Reaction score
62
Jamani nimetengeneza Database yenye Tables kadhaa lakini nimekuwa nikiishia kwenye command hizi tuu kujifurahisha

use mydatabase;
show database;
select *from table1;

na nyinginezo lakini nimeshindwa kabisa kutumia kwa matumizi niliyokusudia.

ndugu zangu naomba anayeelewa jambo hili naomba anielekeze kwamba nitawezaje kuingiza hii Database niliyotengeneza kwenye matumizi ya kawaida na kuachana na Command Prompt...

Nawasilisha jamani...
 
Jamani nimetengeneza Database yenye Tables kadhaa lakini nimekuwa nikiishia kwenye command hizi tuu kujifurahisha

use mydatabase;
show database;
select *from table1;

na nyinginezo lakini nimeshindwa kabisa kutumia kwa matumizi niliyokusudia.

ndugu zangu naomba anayeelewa jambo hili naomba anielekeze kwamba nitawezaje kuingiza hii Database niliyotengeneza kwenye matumizi ya kawaida na kuachana na Command Prompt...

Nawasilisha jamani...

Labda wewe ulikusudia kutumia kwa matumizi gani? Ili kuanzia hapo tujue namna ya kukusaidia
 
Labda wewe ulikusudia kutumia kwa matumizi gani? Ili kuanzia hapo tujue namna ya kukusaidia

application ya kwenye kompyata. ladba tuseme database inayoonyesha bidhaa zilizopo katika duka au maduka fulani.
 
application ya kwenye kompyata. ladba tuseme database inayoonyesha bidhaa zilizopo katika duka au maduka fulani.

je hiyo database unataka ifanye kazi kwenye web based apps au kwenye software uliyotengeneza mwenyewe au unamaanisha nini?
 
na mimi nina tatizo kama hilo hilo...nimetengeza database kutumia 000webhost.com nataka kutengeneza registration form za website yangu....naomba muongozo nifanyeje.kwani nimetengeza tu database tu but sijaweka tables zozote wala sijui nianzie wapi kufanikisha hilo
 
na mimi nina tatizo kama hilo hilo...nimetengeza database kutumia 000webhost.com nataka kutengeneza registration form za website yangu....naomba muongozo nifanyeje.kwani nimetengeza tu database tu but sijaweka tables zozote wala sijui nianzie wapi kufanikisha hilo
 
Jamani nimetengeneza Database yenye Tables kadhaa lakini nimekuwa nikiishia kwenye command hizi tuu kujifurahisha

use mydatabase;
show database;
select *from table1;

na nyinginezo lakini nimeshindwa kabisa kutumia kwa matumizi niliyokusudia.

ndugu zangu naomba anayeelewa jambo hili naomba anielekeze kwamba nitawezaje kuingiza hii Database niliyotengeneza kwenye matumizi ya kawaida na kuachana na Command Prompt...

Nawasilisha jamani...
Pole,kaka kwa maelezo yako inaonyesha SQL bado haujaimaster,unajua sehemu nyingi utapata tutorial zitakufundisha sql ila nying wataelezea command za sql,inner join,outer join, creating views.Kwa kifupi unatakiwa ujifunze zaidi kwa kufanya kiproject kidogo ili uone je unaweza weka new information kwenye database,je unaweza retrieve information kutoka kwenye database na zikaja ulivyozikusudia.
Take your time jifue vya kutosha usiwe na haraka,kama hicho tu ndiyo ulichoweza kufanya bado unahitaji kujifua zaidi.
"It is better to have no job than to have a job when you are not prepared".
Jifue zaidi,tafuta material ya SQL,jiunge na forum za sql utaweza kufanya hicho unachotaka.
Ni vigumu sana kukuelekeza kwa kuandika.
Front end unatumia language ipi?(user iinterface unatengeneza kwa kutumia nini?).
Kwa kuanza nenda tizag you will get something on sql.
 
na mimi nina tatizo kama hilo hilo...nimetengeza database kutumia 000webhost.com nataka kutengeneza registration form za website yangu....naomba muongozo nifanyeje.kwani nimetengeza tu database tu but sijaweka tables zozote wala sijui nianzie wapi kufanikisha hilo

Kama unatumia 000webhost, wanayo phpMyAdmin unaeza kutumia kumanage ur databases na tables. Na hao wanakuwa MySQL, so pia jaribu ku-google tutorial za MySQL on youtube I am so sure zimejaa
 
Jamani nimetengeneza Database yenye Tables kadhaa lakini nimekuwa nikiishia kwenye command hizi tuu kujifurahisha

use mydatabase;
show database;
select *from table1;

na nyinginezo lakini nimeshindwa kabisa kutumia kwa matumizi niliyokusudia.

ndugu zangu naomba anayeelewa jambo hili naomba anielekeze kwamba nitawezaje kuingiza hii Database niliyotengeneza kwenye matumizi ya kawaida na kuachana na Command Prompt...

Nawasilisha jamani...

Nadhani unataka kuunganisha na app yako. Sasa inategemea ni app ya aina gani. Wep app, desktop, mobile. Pia lazima ujue ni dbms gani unataka kutumia MySQL, MS SQL na nyengine. Kamatafute bucky on youtube, new boston tutorials atakusaidia. thenewboston - YouTube
 
Itabidi uandike application itayounga na hiyo DB, hii inakuwa kama inaficha complexity kwa mtumiaji wa kawaida, unaweza kuandika kwenye lugha karibia yoyote unayotaka wewe na jinsi ya kufanya hivyo itatofautiana kulingana na lugha utayotumia na database unayotumia. Jaribu kuangalia MS Access (Inakuja na Office) hii ni Database application itakayokuwezesha kutunegeneza kila kitu ndani yake, kuanzia DB hadi front end.

Pia kuna Graphic user interface za MySQL ambazo zinakuwezesha kucheza na DB bila kutumia command line cheki MySQL :: Download MySQL Workbench

n4YqviJ.gif
 
Pole,kaka kwa maelezo yako inaonyesha SQL bado haujaimaster,unajua sehemu nyingi utapata tutorial zitakufundisha sql ila nying wataelezea command za sql,inner join,outer join, creating views.Kwa kifupi unatakiwa ujifunze zaidi kwa kufanya kiproject kidogo ili uone je unaweza weka new information kwenye database,je unaweza retrieve information kutoka kwenye database na zikaja ulivyozikusudia.
Take your time jifue vya kutosha usiwe na haraka,kama hicho tu ndiyo ulichoweza kufanya bado unahitaji kujifua zaidi.
"It is better to have no job than to have a job when you are not prepared".
Jifue zaidi,tafuta material ya SQL,jiunge na forum za sql utaweza kufanya hicho unachotaka.
Ni vigumu sana kukuelekeza kwa kuandika.
Front end unatumia language ipi?(user iinterface unatengeneza kwa kutumia nini?).
Kwa kuanza nenda tizag you will get something on sql.

front end natumia c++. yote uliyoandika hapo juu ninauelewa nayo rafiki. lakini asante sana kwa maeleza yako mazuri.
 
front end natumia c++. yote uliyoandika hapo juu ninauelewa nayo rafiki. lakini asante sana kwa maeleza yako mazuri.

Ok.Basi itengeneze database yako ikae vizuri table zote,then uwe unajaribu commands za update,insert,select,create views ambazo zitakuwa na vitu utakavyohitaji kama output.Huko pakikaa vizuri then unatengeneza interface yako unaanza kulink na Db,taratibu utafanikiwa.Jaribu kutafuta videos you tube zitakusaidia zaidi.
 
Jamani nimetengeneza Database yenye Tables kadhaa lakini nimekuwa nikiishia kwenye command hizi tuu kujifurahisha

use mydatabase;
show database;
select *from table1;

na nyinginezo lakini nimeshindwa kabisa kutumia kwa matumizi niliyokusudia.

ndugu zangu naomba anayeelewa jambo hili naomba anielekeze kwamba nitawezaje kuingiza hii Database niliyotengeneza kwenye matumizi ya kawaida na kuachana na Command Prompt...

Nawasilisha jamani...

Unataka kutengeneza database kwa ajili ya matumizi gani?
 
nimepata hii hapa kama mfano. nadhani itakuwa point ya kuanzia...

This tutorial will show you the essential steps to build and install MySQL Connector/C++ driver, with simple examples to connect, insert, and retrieve data from a MySQL database. Because the focus is on database connectivity from a C++ application, this document assumes that some kind of MySQL database is already up and accessible from the client machine.
Application developers who are new to MySQL Connector/C++ but not to C++ programming and MySQL database, are the target audience of this tutorial.
Listed below are the tools and technologies used to compile, build and run the examples in this tutorial.
[TABLE="width: 40, align: center"]
[TR]
[TD]Database
[/TD]
[TD]MySQL Server 5.1.24-rc
[/TD]
[/TR]
[TR]
[TD]C++ Driver
[/TD]
[TD]MySQL Connector/C++ 1.0.5
[/TD]
[/TR]
[TR]
[TD]MySQL Client Library
[/TD]
[TD]MySQL Connector/C 6.0
[/TD]
[/TR]
[TR]
[TD]Compiler
[/TD]
[TD]Sun Studio 12 C++ compiler
[/TD]
[/TR]
[TR]
[TD]Make
[/TD]
[TD]CMake 2.6.3
[/TD]
[/TR]
[TR]
[TD]Operating System
[/TD]
[TD]OpenSolaris 2008.11 32-bit
[/TD]
[/TR]
[TR]
[TD]CPU / ISA
[/TD]
[TD]Intel Centrino / x86
[/TD]
[/TR]
[TR]
[TD]Hardware
[/TD]
[TD]Toshiba Tecra M2 Laptop
[/TD]
[/TR]
[/TABLE]
CONTENTS

MySQL C++ Driver Based on JDBC 4.0 Specification
MySQL Connector/C++ is one of the latest connectors for MySQL, developed by Sun Microsystems. The MySQL connector for C++ provides an object-oriented application programming interface (API) and a database driver for connecting C++ applications to the MySQL Server.
The development of Connector/C++ took a different approach compared to the existing drivers for C++ by implementing the JDBC API in C++ world. In other words, Connector/C++ driver's interface is mostly based on Java programming language's JDBC API. Java Database Connectivity (JDBC) API is the industry standard for connectivity between the Java programming language and a wide range of databases. Connector/C++ implemented a significant percentage of the JDBC 4.0 specification. C++ application developers who are familiar with JDBC programming may find this useful, and as a result, it could improve application development time.
The following classes were implemented by the MySQL Connector/C++.

  • Driver
  • Connection
  • Statement
  • PreparedStatement
  • ResultSet
  • Savepoint
  • DatabaseMetaData
  • ResultSetMetaData
  • ParameterMetaData
The Connector/C++ driver can be used to connect to MySQL 5.1 and later versions.
Prior to MySQL Connector/C++, C++ application developers were required to use either the non-standard & procedural MySQL C API directly or the MySQL++ API, which is a C++ wrapper for the MySQL C API.
Installing MySQL Connector/C++
Binary Installation
Starting with release 1.0.4, Connector/C++ is available in binary form for Solaris, Linux, Windows, FreeBSD, Mac OS X, HP-UX and AIX platforms. MSI installer and a binary zip file without the installer is available for Windows, where as the binary package is available as compressed GNU TAR archive (tar.gz) for the rest of the platforms. You can download the pre-compiled binary from the Connector/C++ download page.
Installation from the binary package is very straight forward on Windows and other platforms - simply unpacking the archive in a desired location installs the Connector/C++ driver. Both statically linked and the dynamically linked Connector/C++ driver can be found in lib directory under the driver installation directory. If you plan to use the dynamically linked version of MySQL Connector/C++, ensure that the runtime linker can find the MySQL Client Library. Consult your operating system documentation for the steps to modify and expand the search path for libraries. In case you cannot modify the library search path, copy your application, the MySQL Connector/C++ driver and the MySQL Client Library into the same directory. This approach may work on most of the platforms as they search the originating directory by default, before searching for the required dynamic libraries elsewhere.
Source Installation
Those who want to build the connector driver from the source code, please check the Installing MySQL Connector/C++ from Source page for detailed instructions.
Runtime Dependencies
Because the Connector/C++ driver is linked against the MySQL Client Library, dynamically linked C++ applications that use Connector/C++ will require the MySQL client programming support installed along with the connector driver, on the machines where the application is supposed to run. Static linking with the MySQL Client Library is one of the options to eliminate this runtime dependency. However due to various reasons, static linking is discouraged in building larger applications.
IDE for Developing C++ Applications
If you are looking for an integrated development environment (IDE) to develop C/C++ applications, consider using the free and open NetBeans platform. NetBeans C/C++ Development Pack lets C/C++ developers use their specified set of compilers and tools in conjunction with NetBeans IDE to build native applications on Solaris, Linux, Windows and Mac OS X. The C/C++ development pack makes the editor language-aware for C/C++ and provides project templates, a dynamic class browser, Makefile support &m debugger functionality. It is possible to extend C/C++ development pack base functionality with new features, modules and plug-ins.
MySQL Connector/C++: How to Build a Client using NetBeans 6.5 (for Dummies) tutorial has instructions to use NetBeans IDE to build client applications based on Connector/C++. In addition to the above tutorial, Installing and Configuring C/C++ Support tutorial on NetBeans.org web site will help you with the installation and configuration steps for the NetBeans C/C++ development pack, and Getting Started With the NetBeans C/C++ Development Pack tutorial provides the basic steps involved in developing a C/C++ application using the NetBeans C/C++ Development Pack.
Create the City Table in the test Database for Code Examples
The code samples in this tutorial try to retrieve the data from the City table in the MySQL test database. The table structure and the data from the City table are shown here by using the mysql client. The MySQL Server is running on the default port 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 was used to show all the examples in this tutorial.
Testing the MySQL Database Connectivity With the Connector/C++
The following C++ code sample demonstrates how to connect to a MySQL Server running on the same host, using the MySQL Connector for C++. The code sample connects to the MySQL database test by using the JDBC like API provided by the Connector C++, executes a query to retrieve all the rows from the table City, extracts the data from the result set and displays it on the standard output, inserts couple of rows of data into the table City using the Prepared Statements, demonstrates transactions using savepoints and examines the result set and database metadata.
The sample code is provided only for the purpose of demonstration. It does not recommend the readers to adopt a particular style of coding. To keep it simple, the sample code assumes that the user always provides well-formed input - hence there is no explicit error checking code in the following example. Use discretion in re-using the sample code. (Download the sample code)

# cat MySQLConnectorC++Client.cpp

/* Standard C++ headers */
#include <iostream>
#include <sstream>
#include <memory>
#include <string>
#include <stdexcept>

/* MySQL Connector/C++ specific headers */
#include <driver.h>
#include <connection.h>
#include <statement.h>
#include <prepared_statement.h>
#include <resultset.h>
#include <metadata.h>
#include <resultset_metadata.h>
#include <exception.h>
#include <warning.h>

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

#define NUMOFFSET 100
#define COLNAME 200

using namespace std;
using namespace sql;

static void retrieve_data_and_print (ResultSet *rs, int type, int colidx, string colname) {

/* retrieve the row count in the result set */
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;

} // 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" << 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;

} // 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" << 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;

} // retrieve_rsmetadata_and_print()


int main(int argc, const char *argv[]) {

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(argc >= 2 ? argv[1] : DBHOST);
const string user(argc >= 3 ? argv[2] : USER);
const string password(argc >= 4 ? argv[3] : PASSWORD);
const string database(argc >= 5 ? argv[4] : 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 */
retrieve_dbmetadata_and_print (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");

cout << "Retrieving the result set .." << endl;

/* retrieve the data from the result set and display on stdout */
retrieve_data_and_print (res, NUMOFFSET, 1, string("CityName"));

/* retrieve and display the result set metadata */
retrieve_rsmetadata_and_print (res);

cout << "Demonstrating Prepared Statements .. " << endl << endl;

/* insert couple of rows of data into City table using Prepared Statements */
prep_stmt = con -> prepareStatement ("INSERT INTO City (CityName) VALUES (?)");

cout << "\tInserting \"London, UK\" into the table, City .." << endl;

prep_stmt -> setString (1, "London, UK");
updatecount = prep_stmt -> executeUpdate();

cout << "\tCreating a save point \"SAVEPT1\" .." << endl;
savept = con -> setSavepoint ("SAVEPT1");

cout << "\tInserting \"Paris, France\" into the table, City .." << endl;

prep_stmt -> setString (1, "Paris, France");
updatecount = prep_stmt -> executeUpdate();

cout << "\tRolling back until the last save point \"SAVEPT1\" .." << endl;
con -> rollback (savept);
con -> releaseSavepoint (savept);

cout << "\tCommitting outstanding updates to the database .." << endl;
con -> commit();

cout << "\nQuerying the City table again .." << endl;

/* re-use result set object */
res = NULL;
res = stmt -> executeQuery ("SELECT * FROM City");

/* retrieve the data from the result set and display on stdout */
retrieve_data_and_print (res, COLNAME, 1, string ("CityName"));

cout << "Cleaning up the resources .." << endl;

/* Clean up */
delete res;
delete stmt;
delete prep_stmt;
con -> close();
delete con;

} catch (SQLException &e) {
cout << "ERROR: SQLException in " << __FILE__;
cout << " (" << __func__<< ") on line " << __LINE__ << endl;
cout << "ERROR: " << e.what();
cout << " (MySQL error code: " << e.getErrorCode();
cout << ", SQLState: " << e.getSQLState() << ")" << endl;

if (e.getErrorCode() == 1047) {
/*
Error: 1047 SQLSTATE: 08S01 (ER_UNKNOWN_COM_ERROR)
Message: Unknown command
*/
cout << "\nYour server does not seem to support Prepared Statements at all. ";
cout << "Perhaps MYSQL < 4.1?" << endl;
}

return EXIT_FAILURE;
} catch (std::runtime_error &e) {

cout << "ERROR: runtime_error in " << __FILE__;
cout << " (" << __func__ << ") on line " << __LINE__ << endl;
cout << "ERROR: " << e.what() << endl;

return EXIT_FAILURE;
}

return EXIT_SUCCESS;
} // main()

# CC -V
CC: Sun C++ 5.9 SunOS_i386 Patch 124864-09 2008/12/16

# CC -o mysqlconnectorc++client -g0 -xO4 -features=extensions -I/opt/coolstack/mysql_32bit/include/mysql \
-I/export/expts/MySQLConnectorC++/include/cppconn -L/opt/coolstack/mysql_32bit/lib/mysql \
-L/export/expts/MySQLConnectorC++/lib -lmysqlclient_r -lmysqlcppconn MySQLConnectorC++Client.cpp

# export LD_LIBRARY_PATH=/opt/coolstack/mysql_32bit/lib/mysql:/export/expts/ConnectorC++/lib/:$LD_LIBRARY_PATH
 
nimepata hii hapa kama mfano. nadhani itakuwa point ya kuanzia...

This tutorial will show you the essential steps to build and install MySQL Connector/C++ driver, with simple examples to connect, insert, and retrieve data from a MySQL database. Because the focus is on database connectivity from a C++ application, this document assumes that some kind of MySQL database is already up and accessible from the client machine.
Application developers who are new to MySQL Connector/C++ but not to C++ programming and MySQL database, are the target audience of this tutorial.
Listed below are the tools and technologies used to compile, build and run the examples in this tutorial.
[TABLE="width: 40, align: center"]
[TR]
[TD]Database
[/TD]
[TD]MySQL Server 5.1.24-rc
[/TD]
[/TR]
[TR]
[TD]C++ Driver
[/TD]
[TD]MySQL Connector/C++ 1.0.5
[/TD]
[/TR]
[TR]
[TD]MySQL Client Library
[/TD]
[TD]MySQL Connector/C 6.0
[/TD]
[/TR]
[TR]
[TD]Compiler
[/TD]
[TD]Sun Studio 12 C++ compiler
[/TD]
[/TR]
[TR]
[TD]Make
[/TD]
[TD]CMake 2.6.3
[/TD]
[/TR]
[TR]
[TD]Operating System
[/TD]
[TD]OpenSolaris 2008.11 32-bit
[/TD]
[/TR]
[TR]
[TD]CPU / ISA
[/TD]
[TD]Intel Centrino / x86
[/TD]
[/TR]
[TR]
[TD]Hardware
[/TD]
[TD]Toshiba Tecra M2 Laptop
[/TD]
[/TR]
[/TABLE]
CONTENTS

MySQL C++ Driver Based on JDBC 4.0 Specification
MySQL Connector/C++ is one of the latest connectors for MySQL, developed by Sun Microsystems. The MySQL connector for C++ provides an object-oriented application programming interface (API) and a database driver for connecting C++ applications to the MySQL Server.
The development of Connector/C++ took a different approach compared to the existing drivers for C++ by implementing the JDBC API in C++ world. In other words, Connector/C++ driver's interface is mostly based on Java programming language's JDBC API. Java Database Connectivity (JDBC) API is the industry standard for connectivity between the Java programming language and a wide range of databases. Connector/C++ implemented a significant percentage of the JDBC 4.0 specification. C++ application developers who are familiar with JDBC programming may find this useful, and as a result, it could improve application development time.
The following classes were implemented by the MySQL Connector/C++.

  • Driver
  • Connection
  • Statement
  • PreparedStatement
  • ResultSet
  • Savepoint
  • DatabaseMetaData
  • ResultSetMetaData
  • ParameterMetaData
The Connector/C++ driver can be used to connect to MySQL 5.1 and later versions.
Prior to MySQL Connector/C++, C++ application developers were required to use either the non-standard & procedural MySQL C API directly or the MySQL++ API, which is a C++ wrapper for the MySQL C API.
Installing MySQL Connector/C++
Binary Installation
Starting with release 1.0.4, Connector/C++ is available in binary form for Solaris, Linux, Windows, FreeBSD, Mac OS X, HP-UX and AIX platforms. MSI installer and a binary zip file without the installer is available for Windows, where as the binary package is available as compressed GNU TAR archive (tar.gz) for the rest of the platforms. You can download the pre-compiled binary from the Connector/C++ download page.
Installation from the binary package is very straight forward on Windows and other platforms - simply unpacking the archive in a desired location installs the Connector/C++ driver. Both statically linked and the dynamically linked Connector/C++ driver can be found in lib directory under the driver installation directory. If you plan to use the dynamically linked version of MySQL Connector/C++, ensure that the runtime linker can find the MySQL Client Library. Consult your operating system documentation for the steps to modify and expand the search path for libraries. In case you cannot modify the library search path, copy your application, the MySQL Connector/C++ driver and the MySQL Client Library into the same directory. This approach may work on most of the platforms as they search the originating directory by default, before searching for the required dynamic libraries elsewhere.
Source Installation
Those who want to build the connector driver from the source code, please check the Installing MySQL Connector/C++ from Source page for detailed instructions.
Runtime Dependencies
Because the Connector/C++ driver is linked against the MySQL Client Library, dynamically linked C++ applications that use Connector/C++ will require the MySQL client programming support installed along with the connector driver, on the machines where the application is supposed to run. Static linking with the MySQL Client Library is one of the options to eliminate this runtime dependency. However due to various reasons, static linking is discouraged in building larger applications.
IDE for Developing C++ Applications
If you are looking for an integrated development environment (IDE) to develop C/C++ applications, consider using the free and open NetBeans platform. NetBeans C/C++ Development Pack lets C/C++ developers use their specified set of compilers and tools in conjunction with NetBeans IDE to build native applications on Solaris, Linux, Windows and Mac OS X. The C/C++ development pack makes the editor language-aware for C/C++ and provides project templates, a dynamic class browser, Makefile support &m debugger functionality. It is possible to extend C/C++ development pack base functionality with new features, modules and plug-ins.
MySQL Connector/C++: How to Build a Client using NetBeans 6.5 (for Dummies) tutorial has instructions to use NetBeans IDE to build client applications based on Connector/C++. In addition to the above tutorial, Installing and Configuring C/C++ Support tutorial on NetBeans.org web site will help you with the installation and configuration steps for the NetBeans C/C++ development pack, and Getting Started With the NetBeans C/C++ Development Pack tutorial provides the basic steps involved in developing a C/C++ application using the NetBeans C/C++ Development Pack.
Create the City Table in the test Database for Code Examples
The code samples in this tutorial try to retrieve the data from the City table in the MySQL test database. The table structure and the data from the City table are shown here by using the mysql client. The MySQL Server is running on the default port 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 was used to show all the examples in this tutorial.
Testing the MySQL Database Connectivity With the Connector/C++
The following C++ code sample demonstrates how to connect to a MySQL Server running on the same host, using the MySQL Connector for C++. The code sample connects to the MySQL database test by using the JDBC like API provided by the Connector C++, executes a query to retrieve all the rows from the table City, extracts the data from the result set and displays it on the standard output, inserts couple of rows of data into the table City using the Prepared Statements, demonstrates transactions using savepoints and examines the result set and database metadata.
The sample code is provided only for the purpose of demonstration. It does not recommend the readers to adopt a particular style of coding. To keep it simple, the sample code assumes that the user always provides well-formed input - hence there is no explicit error checking code in the following example. Use discretion in re-using the sample code. (Download the sample code)

# cat MySQLConnectorC++Client.cpp

/* Standard C++ headers */
#include <iostream>
#include <sstream>
#include <memory>
#include <string>
#include <stdexcept>

/* MySQL Connector/C++ specific headers */
#include <driver.h>
#include <connection.h>
#include <statement.h>
#include <prepared_statement.h>
#include <resultset.h>
#include <metadata.h>
#include <resultset_metadata.h>
#include <exception.h>
#include <warning.h>

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

#define NUMOFFSET 100
#define COLNAME 200

using namespace std;
using namespace sql;

static void retrieve_data_and_print (ResultSet *rs, int type, int colidx, string colname) {

/* retrieve the row count in the result set */
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;

} // 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" << 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;

} // 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" << 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;

} // retrieve_rsmetadata_and_print()


int main(int argc, const char *argv[]) {

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(argc >= 2 ? argv[1] : DBHOST);
const string user(argc >= 3 ? argv[2] : USER);
const string password(argc >= 4 ? argv[3] : PASSWORD);
const string database(argc >= 5 ? argv[4] : 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 */
retrieve_dbmetadata_and_print (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");

cout << "Retrieving the result set .." << endl;

/* retrieve the data from the result set and display on stdout */
retrieve_data_and_print (res, NUMOFFSET, 1, string("CityName"));

/* retrieve and display the result set metadata */
retrieve_rsmetadata_and_print (res);

cout << "Demonstrating Prepared Statements .. " << endl << endl;

/* insert couple of rows of data into City table using Prepared Statements */
prep_stmt = con -> prepareStatement ("INSERT INTO City (CityName) VALUES (?)");

cout << "\tInserting \"London, UK\" into the table, City .." << endl;

prep_stmt -> setString (1, "London, UK");
updatecount = prep_stmt -> executeUpdate();

cout << "\tCreating a save point \"SAVEPT1\" .." << endl;
savept = con -> setSavepoint ("SAVEPT1");

cout << "\tInserting \"Paris, France\" into the table, City .." << endl;

prep_stmt -> setString (1, "Paris, France");
updatecount = prep_stmt -> executeUpdate();

cout << "\tRolling back until the last save point \"SAVEPT1\" .." << endl;
con -> rollback (savept);
con -> releaseSavepoint (savept);

cout << "\tCommitting outstanding updates to the database .." << endl;
con -> commit();

cout << "\nQuerying the City table again .." << endl;

/* re-use result set object */
res = NULL;
res = stmt -> executeQuery ("SELECT * FROM City");

/* retrieve the data from the result set and display on stdout */
retrieve_data_and_print (res, COLNAME, 1, string ("CityName"));

cout << "Cleaning up the resources .." << endl;

/* Clean up */
delete res;
delete stmt;
delete prep_stmt;
con -> close();
delete con;

} catch (SQLException &e) {
cout << "ERROR: SQLException in " << __FILE__;
cout << " (" << __func__<< ") on line " << __LINE__ << endl;
cout << "ERROR: " << e.what();
cout << " (MySQL error code: " << e.getErrorCode();
cout << ", SQLState: " << e.getSQLState() << ")" << endl;

if (e.getErrorCode() == 1047) {
/*
Error: 1047 SQLSTATE: 08S01 (ER_UNKNOWN_COM_ERROR)
Message: Unknown command
*/
cout << "\nYour server does not seem to support Prepared Statements at all. ";
cout << "Perhaps MYSQL < 4.1?" << endl;
}

return EXIT_FAILURE;
} catch (std::runtime_error &e) {

cout << "ERROR: runtime_error in " << __FILE__;
cout << " (" << __func__ << ") on line " << __LINE__ << endl;
cout << "ERROR: " << e.what() << endl;

return EXIT_FAILURE;
}

return EXIT_SUCCESS;
} // main()

# CC -V
CC: Sun C++ 5.9 SunOS_i386 Patch 124864-09 2008/12/16

# CC -o mysqlconnectorc++client -g0 -xO4 -features=extensions -I/opt/coolstack/mysql_32bit/include/mysql \
-I/export/expts/MySQLConnectorC++/include/cppconn -L/opt/coolstack/mysql_32bit/lib/mysql \
-L/export/expts/MySQLConnectorC++/lib -lmysqlclient_r -lmysqlcppconn MySQLConnectorC++Client.cpp

# export LD_LIBRARY_PATH=/opt/coolstack/mysql_32bit/lib/mysql:/export/expts/ConnectorC++/lib/:$LD_LIBRARY_PATH
 
Back
Top Bottom