下面,以一个实例来讲解这个问题:
(1)打开VS2010,【文件】->【新建】->【项目】->【Windows窗体应用程序】,新建一个窗体应用程序,命名为【 vsAcces】
(2)新建一个ACCESS数据库,命名为【MyAccess.mdb】,然后添加一个表,并增加字段【ID】、【name】、【password】,手动录入一些数据,并把这个文件放到【....\vsAcces\bin\Debug】目录下,如下图
(3)给工程添加一个数据库的操作类,在工程【单击右键】->【添加】->【类】,命名为【DatabaseOperate.cs】
(4)在这个类中,我们加入操作数据库的代码
using System;using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.OleDb;
using System.Windows.Forms;
using System.Data;
namespace vsAcces
{
class DatabaseOperate
{
protected OleDbConnection dbconn;//定义数据库连接对象
protected OleDbCommand dbcomm = new OleDbCommand();//定义数据库操作对象
/// <summary>
/// 打开数据库
/// </summary>
/// <returns></returns>
public void CreateDbConn()
{
try
{
/*设置数据库路径*/
string dbpath = AppDomain.CurrentDomain.BaseDirectory
+ @"MyAccess.mdb";
/*初始化数据库连接对象*/
dbconn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + dbpath);
/*设置数据库操作对象使用此dbconn对象*/
dbcomm.Connection = dbconn;
/*打开数据库连接*/
dbconn.Open();
}
catch (OleDbException) //如果出现数据库连接异常,则关闭数据库连接并弹出提示框
{
this.CloseDbConn();//关闭数据库连接
MessageBox.Show("数据连接错误!", "操作提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception) //如果出现其他异常,则关闭数据库连接并弹出提示框
{
this.CloseDbConn(); //关闭数据库连接
MessageBox.Show("数据连接错误!", "操作提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
/// <summary>
/// 关闭数据库
/// </summary>
public void CloseDbConn()
{
if (dbconn.State == ConnectionState.Open) //如果数据库为打开状态,则关闭
{
dbconn.Close();//关闭数据库连接
}
dbconn.Dispose();//释放连接资源
dbcomm.Dispose();//释放操作资源
}
/// <summary>
/// 执行SQL语句
/// </summary>
/// <param name="sqlText">传入的SQL语句</param>
public void ExcuteSql(string sqlText)
{
try
{//捕获异常
CreateDbConn();//建立连接
dbcomm.CommandType = CommandType.Text;//设置操作类型为文本类型
dbcomm.CommandText = sqlText;//设置操作的SQL语句
dbcomm.ExecuteNonQuery();//执行操作
}
catch (Exception) //如果出现异常,则提示错误
{
MessageBox.Show("数据库操作错误!", "操作提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
finally
{
CloseDbConn();//关闭连接
}
}
/// <summary>
/// 判断是否执行成功,返回所影响的行数
/// </summary>
/// <param name="sqlText">传入的SQL语句</param>
/// <returns>影响的行数</returns>
public int ExcuteIntSql(string sqlText)
{
try
{
CreateDbConn();//建立连接
dbcomm.CommandType = CommandType.Text;//设置操作类型
dbcomm.CommandText = sqlText;//设置操作的SQL语句
return dbcomm.ExecuteNonQuery();//执行操作,并返回影响的行数
}
catch (Exception)
{
MessageBox.Show("数据库操作错误!", "操作提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
return 0;//如果出现异常,则返回0
}
finally
{
CloseDbConn();//关闭连接
}
}
/// <summary>
/// 返回查询出的单条数字记录结果
/// </summary>
/// <param name="sqlText">传入的SQL语句</param>
/// <returns>查询出的数字结果</returns>
public int ExcuteScrSql(string sqlText)
{
try
{
CreateDbConn();//建立连接
dbcomm.CommandType = CommandType.Text;//设置操作类型
dbcomm.CommandText = sqlText;//设置操作的SQL语句
return Convert.ToInt32(dbcomm.ExecuteScalar());//执行操作,并返回查询出的结果
}
catch (Exception)
{
return 0;//如果出现异常,则返回0
}
finally
{
CloseDbConn();//关闭连接
}
}
/// <summary>
/// 返回查询出的单条文字记录结果
/// </summary>
/// <param name="sqlText">传入的SQL语句</param>
/// <returns>查询出的文字结果</returns>
public string ExcuteStrScrSql(string sqlText)
{
try
{//捕获异常
CreateDbConn();//建立连接
dbcomm.CommandType = CommandType.Text;//设置操作类型
dbcomm.CommandText = sqlText;//设置操作的SQL语句
return dbcomm.ExecuteScalar().ToString();//执行操作,并返回查询出的结果
}
catch (Exception)
{
return "";//如果出现异常,则返回空字符串
}
finally
{
CloseDbConn();//关闭连接
}
}
/// <summary>
/// 返回查询出的数据表
/// </summary>
/// <param name="sqlText">传入的SQL语句</param>
/// <returns>查询出的数据表</returns>
public DataTable GetDataTable(string sqlText)
{
OleDbDataAdapter dbdapt = new OleDbDataAdapter();//实例化一个数据缓存适配器
DataTable dt = new DataTable();//实例化一个数据表
try
{//捕获异常
CreateDbConn();//建立连接
dbcomm.CommandType = CommandType.Text;//设置操作类型
dbcomm.CommandText = sqlText;//设置操作的SQL语句
dbdapt.SelectCommand = dbcomm;//执行SQL语句,选择出数据
dbdapt.Fill(dt);//填充数据表
}
catch (Exception)
{
MessageBox.Show("数据库操作错误!", "操作提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
finally
{
CloseDbConn();//关闭连接
}
return dt;//返回查询出的数据表
}
/// <summary>
/// 按指定条数读出的Table数据表
/// </summary>
/// <param name="sqlText">传入的SQL</param>
/// <param name="pre">开始读数据的记录号</param>
/// <param name="maxcunt">所要读出的最大条数</param>
/// <returns>返回一数据表</returns>
public DataTable GetPageDataTable(string sqlText, int pre, int maxcunt)
{
OleDbDataAdapter dbdapt = new OleDbDataAdapter();//实例化一个数据缓存适配器
DataSet ds = new DataSet();//实例化一个数据缓存器
try
{//捕获异常
CreateDbConn();//建立连接
dbcomm.CommandType = CommandType.Text;//设置操作类型
dbcomm.CommandText = sqlText;//设置操作的SQL语句
dbdapt.SelectCommand = dbcomm;//执行操作,选择出数据
dbdapt.Fill(ds, pre, maxcunt, "db_Table");//按指定的条数填充数据表
}
catch (Exception)
{
}
finally
{
CloseDbConn();//关闭连接
}
return ds.Tables["db_Table"];//返回数据表
}
}
}
(5)现在,我们演示一下如何把数据显示到窗体上
我们在工程【Form1】的窗体上,添加一个【DataGridView控件】,并命名为DGV,再添加一个3个【button控件】,分别是【添加所有】按钮 名为[btnSelectAll]、【删除选中行】按钮 名为[btnDelSelect]、查询【第二条和第三条】按钮 名为[btnTwoToThree]
(6)分别双击这三个按钮,分别进入click方法,然后写入如下代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace vsAcces
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
/*设置DataGridView选中的时候是选中一整行*/
this.DGV.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
}
private void btnSelectAll_Click(object sender, EventArgs e)
{
/*数据库操作对象*/
DatabaseOperate dbo = new DatabaseOperate();
/*执行的SQL语句*/
String sql = "select * from Info";
/*数据表对象*/
DataTable dt = new DataTable();
/*执行SQL语句*/
dt = dbo.GetDataTable(sql);
/*如果查询到数据,则绑定*/
if (dt.Rows.Count > 0)
{
DGV.DataSource = dt;
}
}
private void btnDelSelect_Click(object sender, EventArgs e)
{
/*数据库操作对象*/
DatabaseOperate dbo = new DatabaseOperate();
/*判断DataGridView中是否有数据,通过选中的行来判断 */
if (0 < DGV.SelectedRows.Count)
{
/*获取id*/
int index = (int)DGV.CurrentRow.Index; //获取当前选定行的下标
int id = (int)DGV.Rows[index].Cells[0].Value; //获取当前选定行的第1列的值
String sql = "delete from Info where ID = " + id;
/*执行并判断是否执行成功*/
if (dbo.ExcuteIntSql(sql) < 0)
{
MessageBox.Show("执行失败!");
}
/*刷新*/
btnSelectAll_Click(null, null);
}
}
private void btnTwoToThree_Click(object sender, EventArgs e)
{
/*数据库操作类*/
DatabaseOperate dbo = new DatabaseOperate();
/*执行的SQL语句*/
String sql = "select * from Info";
/*数据表对象*/
DataTable db = new DataTable();
/*执行查询,把查询到的数据放到数据表中*/
db = dbo.GetPageDataTable(sql, 1, 2);
/*关联到DataGridView中*/
DGV.DataSource = db;
}
}
}
(7)至此,我们就完成了,按下键盘【Ctrl+F5】,看一个运行后的效果
学会分享,学会做人,我是 绿色流氓兔 QQ:929955289