Solved

How do I create and drop MySQL tables with C++ code?

Posted on 2007-11-26
11
384 Views
Last Modified: 2010-04-21
I would like some sample C++ code to create a MySQL database, create tables, show tables, drop tables, and execute queries.  I know MySQL commands but am new to C++.
Thank you in advance.
0
Comment
Question by:chaticathe
11 Comments
 
LVL 20

Expert Comment

by:ikework
ID: 20351542
hi chaticathe,

you need an api to access the db .. ODBC, Mysql-Api, Ado or something .. did you choose one already?

ike
0
 
LVL 20

Expert Comment

by:ikework
ID: 20351570
here is a tutorial for the mysql-api:

http://www.geocities.com/jahan.geo/mysql_c_by_example.html

0
 
LVL 39

Expert Comment

by:itsmeandnobodyelse
ID: 20351631
When using ODBC you could pass the 'drop table' SQL command by calling SQLExecDirect(...). If using MYSql library you should have a similar function to invoke any command that doesn't need to return a result set.

Regards, Alex
0
 

Author Comment

by:chaticathe
ID: 20351635
I am using the connection object in the Mysql ++ library.
0
 
LVL 20

Expert Comment

by:ikework
ID: 20351892
there is a tutorial with examples at:

http://tangentsoft.net/mysql++/doc/html/userman/

there are examples included in the library-folder .. dont you have them in your installed folder?

0
PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

 
LVL 20

Expert Comment

by:ikework
ID: 20351905
this is example/custom1.cpp .. a simple query
/***********************************************************************

 custom1.cpp - Example that produces the same results as simple1, but it

 	uses a Specialized SQL Structure to store the results instead of a

	MySQL++ Result object.

 

 Copyright (c) 1998 by Kevin Atkinson, (c) 1999, 2000 and 2001 by

 MySQL AB, and (c) 2004, 2005 by Educational Technology Resources, Inc.

 Others may also hold copyrights on code in this file.  See the CREDITS

 file in the top directory of the distribution for details.
 

 This file is part of MySQL++.
 

 MySQL++ is free software; you can redistribute it and/or modify it

 under the terms of the GNU Lesser General Public License as published

 by the Free Software Foundation; either version 2.1 of the License, or

 (at your option) any later version.
 

 MySQL++ is distributed in the hope that it will be useful, but WITHOUT

 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or

 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public

 License for more details.
 

 You should have received a copy of the GNU Lesser General Public

 License along with MySQL++; if not, write to the Free Software

 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301

 USA

***********************************************************************/
 

#include "stock.h"

#include "util.h"
 

#include <iostream>

#include <vector>
 

using namespace std;
 

int

main(int argc, char *argv[])

{

	// Wrap all MySQL++ interactions in one big try block, so any

	// errors are handled gracefully.

	try {						

		// Establish the connection to the database server.

		mysqlpp::Connection con(mysqlpp::use_exceptions);

		if (!connect_to_db(argc, argv, con)) {

			return 1;

		}
 

		// Retrieve the entire contents of the stock table, and store

		// the data in a vector of 'stock' SSQLS structures.

		mysqlpp::Query query = con.query();

		query << "select * from stock";

		vector<stock> res;

		query.storein(res);
 

		// Display the result set

		print_stock_header(res.size());

		vector<stock>::iterator it;

		for (it = res.begin(); it != res.end(); ++it) {

			print_stock_row(it->item, it->num, it->weight, it->price,

					it->sdate);

		}

	}

	catch (const mysqlpp::BadQuery& er) {

		// Handle any query errors

		cerr << "Query error: " << er.what() << endl;

		return -1;

	}

	catch (const mysqlpp::BadConversion& er) {

		// Handle bad conversions; e.g. type mismatch populating 'stock'

		cerr << "Conversion error: " << er.what() << endl <<

				"\tretrieved data size: " << er.retrieved <<

				", actual size: " << er.actual_size << endl;

		return -1;

	}

	catch (const mysqlpp::Exception& er) {

		// Catch-all for any other MySQL++ exceptions

		cerr << "Error: " << er.what() << endl;

		return -1;

	}
 

	return 0;

}

Open in new window

0
 

Author Comment

by:chaticathe
ID: 20351911
Yes, I had just found them.  Thank you for your quick response.  
0
 
LVL 55

Expert Comment

by:Jaime Olivares
ID: 20351912
if you know mySQL, then you know how to create tables with a query. So, you just need an example of MySQL++:
http://www.downloadjunction.com/product/store/6969/index.html
http://www.rdrop.com/docs/mysql/4_Tutorial.html
0
 
LVL 20

Accepted Solution

by:
ikework earned 500 total points
ID: 20351926
example with show tables:
/***********************************************************************

 dbinfo.cpp - Example showing how to request information about the

	database schema, such as table names, column types, etc.
 

 Copyright (c) 1998 by Kevin Atkinson, (c) 1999, 2000 and 2001 by

 MySQL AB, and (c) 2004, 2005 by Educational Technology Resources, Inc.

 Others may also hold copyrights on code in this file.  See the CREDITS

 file in the top directory of the distribution for details.
 

 This file is part of MySQL++.
 

 MySQL++ is free software; you can redistribute it and/or modify it

 under the terms of the GNU Lesser General Public License as published

 by the Free Software Foundation; either version 2.1 of the License, or

 (at your option) any later version.
 

 MySQL++ is distributed in the hope that it will be useful, but WITHOUT

 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or

 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public

 License for more details.
 

 You should have received a copy of the GNU Lesser General Public

 License along with MySQL++; if not, write to the Free Software

 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301

 USA

***********************************************************************/
 

#include "util.h"
 

#include <mysql++.h>
 

#include <iomanip>

#include <iostream>

#include <string>

#include <vector>
 

using namespace std;

using namespace mysqlpp;
 

vector<string> yy;
 

static ostream&

separator(ostream& os)

{

	os << endl << "---------------------------" << endl << endl;

	return os;

}
 

int

main(int argc, char* argv[])

{

	Connection con(use_exceptions);

	try {

		connect_to_db(argc, argv, con, "");
 

		// Show MySQL version

		cout << "MySQL version: " << con.client_info() << separator;

		Query query = con.query();
 

		// Show all the databases we can see

		query << "show databases";

		cout << "Query: " << query.preview() << endl;
 

		Result res = query.store();

		cout << "Databases found: " << res.size();
 

		Row row;

		cout.setf(ios::left);

		Result::iterator i;

		for (i = res.begin(); i != res.end(); ++i) {

			row = *i;

			cout << endl << '\t' << setw(17) << row.at(0);

		}

		cout << separator;

		

		// Show the tables in the mysql database

		con.select_db("mysql");
 

		query.reset();

		query << "show tables";

		cout << "Query: " << query.preview() << endl;
 

		res = query.store();

		cout << "Tables found: " << res.size();
 

		cout.setf(ios::left);

		for (i = res.begin(); i != res.end(); ++i) {

			row = *i;

			string xx(row.at(0));

			cout << endl << '\t' << setw(17) << row.at(0);

			yy.push_back(xx);

		}

		cout << separator;
 

		// Show information about each of the tables we found

		for (unsigned int j = 0; j < yy.size(); ++j) {

			query.reset();

			query << "describe " << yy[j] << "";

			cout << "Query: " << query.preview() << endl;

			res = query.store();

			unsigned int columns = res.num_fields(), counter;

			vector<int> widths;

			for (counter = 0; counter < columns; counter++) {

				string s = res.names(counter);

				if (s.compare("field") == 0) {

					widths.push_back(22);

				}

				else if (s.compare("type") == 0) {

					widths.push_back(20);

				}

				else if (s.compare("null") == 0) {

					widths.push_back(4);

				}

				else if (s.compare("key") == 0) {

					widths.push_back(3);

				}

				else if (s.compare("extra") == 0) {

					widths.push_back(0);

				}

				else {

					widths.push_back(15);

				}
 

				if (widths[counter]) {

					cout << '|' << setw(widths[counter]) <<

							res.names(counter) << '|';

				}

			}

			cout << endl;
 

			for (i = res.begin(); i != res.end(); ++i) {

				row = *i;

				for (counter = 0; counter < columns; counter++) {

					if (widths[counter]) {

						cout << ' ' << setw(widths[counter]) <<

								row.at(counter) << ' ';

					}

				}

				cout << endl;

			}
 

			cout << separator;

		}
 

		// Show the user table contents

		query.reset();

	 	query << "select * from user";

		cout << "Query: " << query.preview() << endl << endl;
 

		res = query.store();

		int columns = res.num_fields();

		cout << "fields = " << res.num_fields() << ", rows = " <<

				res.size() << endl;

		volatile MYSQL_RES* ress = res.raw_result();

		if (!ress)

			return -1;

		for (i = res.begin(); i != res.end(); ++i) {

			row = *i;

			for (int counter = 0; counter < columns; counter++) {

				cout << row.at(counter) << "  ";

			}

			cout << endl;

		}

	}

	catch (const BadQuery& er) {

		// Handle any query errors

		cerr << "Query error: " << er.what() << endl;

		return -1;

	}

	catch (const BadConversion& er) {

		// Handle bad conversions

		cerr << "Conversion error: " << er.what() << endl <<

				"\tretrieved data size: " << er.retrieved <<

				", actual size: " << er.actual_size << endl;

		return -1;

	}

	catch (const Exception& er) {

		// Catch-all for any other MySQL++ exceptions

		cerr << "Error: " << er.what() << endl;

		return -1;

	}
 

	return 0;

}

Open in new window

0
 
LVL 20

Expert Comment

by:ikework
ID: 20351955
you're welcome .. good luck .. :)
0
 

Author Closing Comment

by:chaticathe
ID: 31411020
Thank you...that is exactly what I was looking for.
0

Featured Post

Zoho SalesIQ

Hassle-free live chat software re-imagined for business growth. 2 users, always free.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

This article describes how to use the timestamp of existing data in a database to allow Tableau to calculate the prior work day instead of relying on case statements or if statements to calculate the days of the week.
Container Orchestration platforms empower organizations to scale their apps at an exceptional rate. This is the reason numerous innovation-driven companies are moving apps to an appropriated datacenter wide platform that empowers them to scale at a …
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.

910 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now