简单的C# 连接MySQL

原创
2013/05/14 15:49
阅读数 422

这是一个简单的用VS2005实现的连接MySQL的小程序

界面如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;

namespace mysqlv
{
    public partial class Form1 : Form
    {
        MySqlConnection myconn;
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                myconn = new MySqlConnection("Data Source=localhost;Initial Catalog=abc;" + "User ID=root;PWD=***");
                myconn.Open();
            }
            catch (MySqlException myerror) {
                MessageBox.Show("MySQL connection error:"+ myerror.Message);
                this.Close();
            }
            button2.Enabled = true;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            MySqlCommand com;
            MySqlDataReader dr;
            com = new MySqlCommand("select name,sex,birth,birthaddr from user",myconn);
            dr = com.ExecuteReader();
            while (dr.Read())
                textBox1.AppendText("name=" + dr["name"] + ",sex=" + dr["sex"] + ",birth=" + dr["birth"] + ",birthaddr=" + dr["birthaddr"] + Environment.NewLine);
            dr.Close();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            this.Close();
        }

    }
}

展开阅读全文
打赏
0
6 收藏
分享
加载中
更多评论
打赏
0 评论
6 收藏
0
分享
返回顶部
顶部