1. Computing & Technology

Discuss in my forum

David Bolton

Creating MySQL Tables from C#

By , About.com GuideMay 22, 2011

Follow me on:

As part of the work I've been doing I wanted a way to create a whole stack of tables in a MySQL database from a C# program that is running on Windows (but soon enough on Mono). The MySql server is running on a networked PC. (Yes that same Ubuntu box).

There are multiple ways of doing this. You could for instance have lots of sql files, loaded one by one and run against the database; but don't try unless you've got a good version control system. Or one big sql file that creates everything but that way gets messy if there are errors and you have to start editing and running individual parts. I went for way three, do it all in code. No messy sql text file maintenance but any changes need a new compile.

The code to create a table looks a little like this:

DbBuilder dbb = new DbBuilder() ;
dbb.StartTable("MyTable") ;
dbb.AddColumn(DbBuilder.ColTypes.ctint, "indexnum", isPrimary: true, isnull: false) ;
dbb.AddColumn(DbBuilder.ColTypes.ctint, "status") ;
dbb.AddColumn(DbBuilder.ColTypes.ctdatetime, "datecreated") ;
sql = dbb.BuildSQL() ;
db.Exec(sql) ;

It's a 217 line C# program that compiles and runs in Visual C# 2010 Express (Yes the free version). Instructions on using the program and explaining how it works are on the link below. Have fun!

Comments
May 23, 2011 at 12:18 am
(1) David :

Would you do a sound tutorial for C++?

Leave a Comment

Line and paragraph breaks are automatic. Some HTML allowed: <a href="" title="">, <b>, <i>, <strike>
Related Searches mysql tables

©2012 About.com. All rights reserved.

A part of The New York Times Company.