I 数据库操作类:
class DataSolve
{
#region 连接数据库的字符串
private string strCon = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\Projects\C#\RemMoneySys\RemMoneySys.mdb;Persist Security Info=False";
#endregion
#region 类中的全局变量
private OleDbConnection oledbCon;//申明一个SqlConnection对象
private OleDbCommand oledbCom; //申明一个SqlCommand对象
private OleDbDataAdapter oledbAda; //申明一个SqlDataAdapter对象
#endregion
#region 构造函数 初始化数据库
///<summary>
///
///</summary>
public DataSolve()
{
oledbCon = new OleDbConnection(strCon);
oledbCon.Open();
}
#endregion
#region 执行SQL语句 返回值成功与否
///<summary>
///
///</summary>
public bool ExceSQL(string sql)
{
try
{
oledbCom = new OleDbCommand(sql, oledbCon);
oledbCom.ExecuteNonQuery();
return true;
}
catch
{
return false;
}
finally
{
oledbCon.Close();
}
}
#endregion
#region 返回dataset集
public DataSet GetDataSet(string sql)
{
try
{
oledbCom = new OleDbCommand(sql, oledbCon);
oledbAda = new OleDbDataAdapter();
oledbAda.SelectCommand =oledbCom;
DataSet ds = new DataSet();
oledbAda.Fill(ds);
return ds;
}
finally
{
oledbCon.Close();
}
}
#endregion
#region
public DataTable GetDataTable(string sql)
{
DataSet ds = new DataSet();
try
{
oledbCom = new OleDbCommand(sql, oledbCon);
OleDbDataAdapter ad = new OleDbDataAdapter(oledbCom);
ad.Fill(ds);
return ds.Tables[0];
}
finally
{
oledbCon.Close();
}
}
#endregion
#region
public OleDbDataReader GetDataReader(string sql)
{
oledbCom = new OleDbCommand(sql, oledbCon);
OleDbDataReader read = oledbCom.ExecuteReader() ;
return read;
}
#endregion
}
II DataGridView控件和Combobox控件的命名grid与cbox,绑定数据代码如下:
DataSolve da = new DataSolve();
DataTable dt = da.GetDataTable("select * from student");
grid.DataSource = dt;
DataSolve da1 = new DataSolve();
DataSet ds = da1.GetDataSet("select * from student");
cbox.DataSource = ds.Tables[0];
cbox.DisplayMember = "name";//绑定数据中的某一列
III实现数据的绑定