求告知如何用C# 在Microsoft Visual Studio 2010 编写一段代码连接Access数据库,和如何更改数据库内容?

2024-11-19 03:31:25
推荐回答(1个)
回答1:

在你的项目中创建一个类,名称为CMyAccessLib,然后把下面的代码填进去,就可以用了,主要可以看看getDataTable,getDataSet,executeCmd等函数的用法就行了,希望对你有用。

using System;
using System.Data;
using System.Data.OleDb;

///


/// Access数据库访问类,By:王宏伟,2012-10-9
/// Email:whw19860424@163.com
///

class
{
private bool m_bStatus;
private OleDbConnection m_conn;
private void init()
{
m_bStatus = false;
if (m_conn != null && m_conn.GetType() == typeof(OleDbConnection) && m_conn.State == ConnectionState.Open)
{
m_conn.Close();
}
m_conn = null;
}
///
/// 数据操作类状态
///

public bool isOK
{
get { return m_bStatus; }
}
///
/// 默认构造函数
///

public CMyAccessLib()
{
init();
}
///
/// 根据Access文件地址及访问密码实例化对象
///

/// Access文件地址
/// Access数据库密码
public CMyAccessLib(string _mdbPath, string _mdbPass)
{
init();
if (!openConnection(_mdbPath, _mdbPass))
{
return;
}
m_bStatus = true;
}
///
/// 打开数据库连接
///

/// Access文件地址
/// Access数据库密码
///
public bool openConnection(string _mdbPath, string _mdbpass)
{
if (_mdbPath.Trim().Equals(string.Empty))
{
return false;
}
if (!System.IO.File.Exists(_mdbPath))
{
return false;
}
m_conn = new OleDbConnection();
m_conn.ConnectionString = m_conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + _mdbPath + ";Jet OLEDB:Database Password=" + _mdbpass;
try
{
m_conn.Open();
m_bStatus = true;
}
catch (Exception e)
{
e = null;
m_bStatus = false;
m_conn = null;
}
return m_bStatus;
}
///
/// 根据SQL语句查询数据库,以out方式传出结果集合DataSet
///

/// SQL查询语句
/// 传出参数,DataSet型查询结果
/// 函数是否执行成功
public bool getDataSet(string _sqlCommand, out DataSet _result)
{
_result = null;
if (!m_bStatus || _sqlCommand.Trim().Equals(string.Empty))
{
return false;
}
try
{
OleDbDataAdapter da = new OleDbDataAdapter(new OleDbCommand(_sqlCommand, m_conn));
_result = new DataSet();
da.Fill(_result);
da.Dispose();
return true;
}
catch (Exception e)
{
e = null;
return false;
}
}
///
/// 根据SQL语句查询数据库,以out形式传出结果表DataTable
///

/// SQL查询语句
/// 传出参数,DataTable型查询结果
/// 函数是否执行成功
public bool getDataTable(string _sqlCommand, out DataTable _result)
{
_result = null;
if (!m_bStatus || _sqlCommand.Trim().Equals(string.Empty))
{
return false;
}
try
{
OleDbDataAdapter da = new OleDbDataAdapter(new OleDbCommand(_sqlCommand, m_conn));
_result = new DataTable();
da.Fill(_result);
da.Dispose();
return true;
}
catch (Exception e)
{
e = null;
return false;
}
}
///
/// 执行SQL命令语句用,不返回查询结果
///

/// SQL查询语句
/// 函数是否执行成功
public bool executeSQLCmd(string _sqlCommand)
{
if (!m_bStatus || _sqlCommand.Trim().Equals(string.Empty))
{
return false;
}
try
{
OleDbCommand cmd = new OleDbCommand(_sqlCommand, m_conn);
cmd.ExecuteNonQuery();
return true;
}
catch (Exception e)
{
e = null;
return false;
}
}
///
/// 清除对象
///

public void Dispose()
{
if (m_conn.State == ConnectionState.Connecting)
{
m_conn.Close();
m_conn.Dispose();
}
init();
}
~CMyAccessLib() { }
}