c#连接Access 数据库需要System.Data, System.Data.OleDb
using System.Data
using System.Data.OleDb
public OleDbConnection getConn()
{
string connstr="Provider=Microsoft.Jet.OLEDB.4.0 ;Data Source=D:\\test\\distance.mdb";
OleDbConnection conn= new OleDbConnection(connstr);
return(conn);
}
建立数据表
private void Createtable()
{ OleDbConnection conn = null; ;
try
{ conn = getConn();
string strAccessCreatetables = "create table distance (ID int NOT NULL, PicName varchar(255) NOT NULL)";
OleDbCommand myCommand = new OleDbCommand(strAccessCreatetables, conn);
conn.Open();
}
catch (Exception ex)
{
MessageBox.Show("Error: Failed to create table.\n{0}", ex.Message);
}
finally
{
conn.Close();
}
}
插入元素
private void AddNote(string picname)
{
try
{
OleDbConnection conn = getConn();
conn.Open();
string insertstr = "insert into distance values(1,'" + picname + "')";
OleDbCommand insertcmd = new OleDbCommand(insertstr, conn);
insertcmd.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error: Failed to insert.\n{0}", ex.Message);
}
}
注意如果在window x64 或 anyCPU 下运行会出错提示: 未在本机计算机上注册“,改成x86 即可,或者x64 下使用ADOX,需加入两个引用Interop.ADODB, Interop.ADOX即可
public static bool CreateMDBDataBase(string mdbPath)
{
try
{
ADOX.CatalogClass cat = new ADOX.CatalogClass();
cat.Create("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + mdbPath + ";");
cat = null;
return true;
}
catch { return false; }
}