Solved

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

Posted on 2007-11-26
11
397 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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
Microsoft Certification Exam 74-409

Veeam® is happy to provide the Microsoft community with a study guide prepared by MVP and MCT, Orin Thomas. This guide will take you through each of the exam objectives, helping you to prepare for and pass the examination.

 

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
 
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

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

If you find yourself in this situation “I have used SELECT DISTINCT but I’m getting duplicates” then I'm sorry to say you are using the wrong SQL technique as it only does one thing which is: produces whole rows that are unique. If the results you a…
When table data gets too large to manage or queries take too long to execute the solution is often to buy bigger hardware or assign more CPUs and memory resources to the machine to solve the problem. However, the best, cheapest and most effective so…
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

749 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