之前用MFC开发结果界面太难看被pass了,要求用C#重新来开发>_<,不过终于摆脱VC6.0的蛋疼操作了Y。
先来连接数据库
(1)用c#连接MySQL数据库需要用到mysql-connector-net,这个组件网上查找就可以下载,安装直接按next,按默认路径安装;
(2)新建一个Winfrom工程后,引用这个组件
在解决方案资源管理器中右键引用->添加引用->浏览,浏览路径为安装mysql-connector-net的路径,如我的路径为:C:\Program Files (x86)\MySQL\MySQL Connector Net 6.6.4\Assemblies\v2.0
选择MySql.Data.dll,再确定
(3)在工程中添加:
using MySql.Data.MySqlClient; using System.Data.SqlClient;
(4)
这里进行简单的页面布局,用了一个按钮,一个listview控件,一个dataGridView控件,其中listview控件名字为listview1,dataGridView控件名字为dataGridView1
(4)对listView进行简单的设计来适合数据呈现:
在属性中选择GridLines改为true
新建一个函数如下:
private void bindListCiew()
{
this.listView1.Columns.Add("学生"); this.listView1.Columns.Add("ID"); this.listView1.View = System.Windows.Forms.View.Details; }
添加两列 学生,ID 实际情况可以根据需求添加;
注意加上this.listView1.View = System.Windows.Forms.View.Details;
否则不会有变化
再
private void Form1_Load(object sender, EventArgs e) { bindListCiew(); }
(5)为按钮添加函数:
private void button1_Click(object sender, EventArgs e)
{
MySqlConnection myconn = null; MySqlCommand mycom = null; MySqlDataAdapter myrec = null; myconn = new MySqlConnection("Host =localhost;Database=student;Username=lemon;Password=123"); myconn.Open(); mycom = myconn.CreateCommand(); mycom.CommandText = "SELECT *FROM student1"; MySqlDataAdapter adap = new MySqlDataAdapter(mycom); DataSet ds = new DataSet(); adap.Fill(ds); dataGridView1.DataSource = ds.Tables[0].DefaultView; string sql = string.Format("select * from student1 "); mycom.CommandText = sql; mycom.CommandType = CommandType.Text; MySqlDataReader sdr = mycom.ExecuteReader(); int i = 0; while (sdr.Read()) { listView1.Items.Add(sdr[0].ToString()); listView1.Items[i].SubItems.Add(sdr[1].ToString()); i++; } myconn.Close(); }
其中
myconn = new MySqlConnection("Host =localhost;Database=****;Username=***;Password=***"); myconn.Open();
为数据库的连接,输入Database,username,password
mycom = myconn.CreateCommand(); mycom.CommandText = "SELECT *FROM student1"; MySqlDataAdapter adap = new MySqlDataAdapter(mycom); DataSet ds = new DataSet(); adap.Fill(ds); dataGridView1.DataSource = ds.Tables[0].DefaultView;
生成一个command 查询数据添加到dataGridView中,这里简单地将数据全部添加进控件中,这个控件打印出来的表格不怎么好看,觉得还是listview好看
剩下的代码是进行listview的显示
其中
listView1.Items.Add(sdr[0].ToString()); listView1.Items[i].SubItems.Add(sdr[1].ToString()); i++;
这是对行的数据的添加;
最后的结果为:
在student1表中我数据为:
开发起来比vc6.0起来好一点;
这世界上的一切罪与罚,我们都会一起承受。