C#操作mdb数据库文件
源码如下:
namespace CSharpWindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private string _fileName;
private string _connectionString;
private OleDbConnection _odcConnection;
private void button1_Click(object sender, EventArgs e)
{
//根据IMEI 862075035979565 进行查找
string exefilepath = System.IO.Directory.GetCurrentDirectory();
string mdbfilepath = exefilepath + "\\M02C_KMD_ST2017040801_13000.MDB";
string mdbFile = mdbfilepath;
string strimei = "7762075035979565";
//MAC在数据库文件中的名称
string strMACSection = "";
//IMEI在数据库文件中的名称
string strIMEISection = "";
//SN在数据库文件中的名称
string strSNSection = "";
DataTable dt = new DataTable();
try
{
DataRow dr;
this._fileName = mdbFile;
this._connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + mdbFile + ";";
//1、建立连接 C#操作Access之读取mdb
this._odcConnection = new OleDbConnection(this._connectionString);
//2、打开连接 C#操作Access之读取mdb
this._odcConnection.Open();
//建立SQL查询
OleDbCommand odCommand = _odcConnection.CreateCommand();
//3、输入查询语句 C#操作Access之读取mdb
odCommand.CommandText = "select * from " + "SNTable";
//建立读取
OleDbDataReader odrReader = odCommand.ExecuteReader();
//查询并显示数据
int size = odrReader.FieldCount;
for (int i = 0; i < size; i++)
{
DataColumn dc;
string sstr = odrReader.GetName(i);
sstr.ToLower();
if (0==sstr.IndexOf("MAC"))
{
strMACSection = odrReader.GetName(i);
}
else if (0 == sstr.IndexOf("IMEI"))
{
strIMEISection = odrReader.GetName(i);
}
else if (0 == sstr.IndexOf("SN"))
{
strSNSection = odrReader.GetName(i);
}
else
{
}
dc = new DataColumn(odrReader.GetName(i));
dt.Columns.Add(dc);
}
while (odrReader.Read())
{
dr = dt.NewRow();
for (int i = 0; i < size; i++)
{
string s1 = odrReader.GetName(i);
string s2 = odrReader[s1].ToString();
string s3 = odrReader[s1].ToString();
if (-1 != s1.IndexOf(strIMEISection) && -1 != s3.IndexOf(strimei))
{
//string strMAC = "MAC";
string s4 = odrReader[strMACSection].ToString();
//00:1E:C8:98:9C:F1
//string strSN = "SN";
string s5 = odrReader[strSNSection].ToString();
//M02C17051501447
//关闭连接 C#操作Access之读取mdb
odrReader.Close();
_odcConnection.Close();
return;
}
dr[s1] = s3;
//dr[odrReader.GetName(i)] =
//odrReader[odrReader.GetName(i)].ToString();
}
dt.Rows.Add(dr);
}
//关闭连接 C#操作Access之读取mdb
odrReader.Close();
_odcConnection.Close();
//success = true;
}
catch
{
//success = false;
}
}
}
}
C#操作mdb文件引用的库为
using System.Data;
using System.Data.OleDb;