Solved

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

Posted on 2007-11-26
11
383 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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
I am using the connection object in the Mysql ++ library.
0
 
LVL 20

Expert Comment

by:ikework
Comment Utility
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
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 20

Expert Comment

by:ikework
Comment Utility
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
Comment Utility
Yes, I had just found them.  Thank you for your quick response.  
0
 
LVL 55

Expert Comment

by:Jaime Olivares
Comment Utility
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
Comment Utility
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
Comment Utility
you're welcome .. good luck .. :)
0
 

Author Closing Comment

by:chaticathe
Comment Utility
Thank you...that is exactly what I was looking for.
0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Both Easy and Powerful How easy is PHP? http://lmgtfy.com?q=how+easy+is+php (http://lmgtfy.com?q=how+easy+is+php)  Very easy.  It has been described as "a programming language even my grandmother can use." How powerful is PHP?  http://en.wikiped…
'Between' is such a common word we rarely think about it but in SQL it has a very specific definition we should be aware of. While most database vendors will have their own unique phrases to describe it (see references at end) the concept in common …
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.

763 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

12 Experts available now in Live!

Get 1:1 Help Now