C#连接MySQL数据库

2017/01/27 14:26
阅读数 218
效果查看
在winform框架下,添加using

using MySql.Data.MySqlClient;
主要代码
static string MyconnecString = "Server=115.159.180.185;Database=han;Uid=root;Pwd=123";
控件定义
private System.Windows.Forms. TextBox textBox1;
private System.Windows.Forms. TextBox textBox2;
private System.Windows.Forms. Button btn_lj;
private System.Windows.Forms. Button btn_dq;
private System.Windows.Forms. DataGridView dataGridView1;

private void btn_lj_Click( object sender, EventArgs e)
        {
             textBox1.Text = MyconnecString;
             MySqlConnection con = new MySqlConnection( MyconnecString);
             MySqlCommand cmd = new MySqlCommand();
            con. Open();
            cmd = con. CreateCommand();
            cmd.CommandType = CommandType. Text;
            cmd.CommandText = "INSERT INTO stu VALUES (NULL,'Abcdd','Xuanwumen 10',122,'Abcdd','Xuanwumen 10')";
            cmd. ExecuteNonQuery();
            con. Close();

             btn_lj.Text = "连接完成";
        }

         private void btn_dq_Click( object sender, EventArgs e)
        {

             textBox2.Text = MyconnecString;
             MySqlConnection con = new MySqlConnection( MyconnecString);
             MySqlCommand cmd = new MySqlCommand();
            con. Open();
            cmd = con. CreateCommand();
            cmd.CommandType = CommandType. Text;
             //SELECT * FROM mz;
            cmd.CommandText = "SELECT * FROM stu";
             MySqlDataAdapter adap = new MySqlDataAdapter(cmd);

             DataSet ds = new DataSet();
            adap. Fill(ds);
             //dataGridView1.DataSource = ds.Tables[1].DefaultView;
             dataGridView1.DataSource = ds.Tables[ 0].DefaultView;
            ds. Dispose();

             btn_dq.Text = "读取完成";

        }





展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部