日期:2014-05-16 浏览次数:20468 次

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySQLDriverCS;//引入mysql .net驱动程序
using System.Data;
namespace WindowsFormsApplication3.Common
{
class DB
{
MySQLConnection conn = null;
//构造函数,设置数据库连接 设置数据库编码
public DB()
{
conn = new MySQLConnection(new MySQLConnectionString("localhost", "yindan", "root", "").AsString);//构造连接字符串,连接数据库
conn.Open();//打开连接
MySQLCommand command = new MySQLCommand("SET NAMES gbk",conn);
command.ExecuteNonQuery();
//设置字符编码及执行无返回值的查询,在这里要注意下,在php里面,页面,这个地方,和创建数据库时,编码要保持一致,因为我使用的是utf8编码,我开始的时候,在这里设置的也是utf8,但是在datagridview里显示的是乱码,当我在这里改了之后,就显示正常了,这个我还不太清楚原因,貌似是要想显示中文就需要使用gbk或者是gb2312,个人观点
}
//在这里要注意下,要使用DataSet这个东西,要引入System.Data这个命名空间
public DataSet getPsize()
{
string sql = "select * from pre_home_psize";
MySQLDataAdapter myadp = new MySQLDataAdapter(sql, this.conn);
//声明数据适配器,执行数据查询
DataSet ds = new DataSet();//声明数据集
myadp.Fill(ds, "psize");//把查到的结果填充到数据集中
conn.Close();//关闭连接
return ds;//返回数据集,用于绑定控件作为数据源
}
}
}
using WindowsFormsApplication3.Common;//这个是刚才写的DB类所在的命名空间,需要引用下
private void setting_Load(object sender, EventArgs e)
{
DB db = new DB();//实例化类
this.dataGridView1.DataSource = db.getPsize().Tables["psize"];
//绑定数据源
在这里注意下,如果有朋友有过asp.net的开发的话,一般绑定了dataGridView的数据源之后,还要有DataBind() 绑定下,但是winform中是不需要的,所以,在这里只需要绑定即可,然后,我们按F5运行看下
}