最近做一个项目,为了方便用户使用,希望可以在系统初始化的时候,自动实现MySQL数据库的建库和建表操作。在网上查了很多资料都没有找到合适的,偶尔在一个国外网站上看到了相关的内容,特把实现方法整理如下:
1、用C#实现MySQL建库
- using System.Drawing;
- using System.Windows.Forms;
- using MySql.Data.MySqlClient;
- namespace MySqlDemo
- {
- /// <summary>
- /// 实现MySQL建库
- /// </summary>
- publicclass 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建表
- publicstaticvoid 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();
- }
- }
- }
---------------------
作者:ssharet
来源:CSDN
原文:https://blog.csdn.net/ssharet/article/details/52825185
来源:oschina
链接:https://my.oschina.net/u/4292207/blog/3601107