用C#实现MySQL建库及建表

时间:2021-10-15 08:20:05

最近做一个项目,为了方便用户使用,希望可以在系统初始化的时候,自动实现MySQL数据库的建库和建表操作。在网上查了很多资料都没有找到合适的,偶尔在一个国外网站上看到了相关的内容,特把实现方法整理如下:

1、用C#实现MySQL建库

using System.Drawing;
using System.Windows.Forms;
using MySql.Data.MySqlClient;

namespace MySqlDemo
{
/// <summary>
/// 实现MySQL建库
/// </summary>
public class Form1 : System.Windows.Forms.Form
{

void btnCreateDB(object sender, System.EventArgs e)
{
MySqlConnection conn = new MySqlConnection("Data Source=localhost;Persist Security Info=yes;UserId=root; PWD=你的密码;");
MySqlCommand cmd = new MySqlCommand("CREATE DATABASE 你的数据库名;", conn );

conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
}


2、用C#实现MySQL建表

        public static void AlterTableExample()
{
string connStr = DbWrapper.TestDbWrapper.BuildConnectionString(DbWrapperType.MySql);
string createStatement = "CREATE TABLE Test (Field1 VarChar(50), Field2 Integer)";
string alterStatement = "ALTER TABLE Test ADD Field3 Boolean";

using (MySqlConnection conn = new MySqlConnection(connStr))
{
conn.Open();

// 建表
using (MySqlCommand cmd = new MySqlCommand(createStatement, conn))
{
cmd.ExecuteNonQuery();
}

// 改表或者增加行
using (MySqlCommand cmd = new MySqlCommand(alterStatement, conn))
{
cmd.ExecuteNonQuery();
}
}
}


参考资料:

http://www.daniweb.com/software-development/csharp/threads/237447

http://www.daniweb.com/software-development/csharp/threads/235791

http://forums.mysql.com/read.php?47,214878,214887#msg-214887