C#如何访问Access数据库

2024年11月19日 15:31
有1个网友回答
网友(1):

// 连接
OleDbConnection cn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\\test.mdb;");
cn.Open();
cn.Close();

// 读取数据到DataTable
OleDbConnection cn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\\test.mdb;");
DataTable userTbl = new DataTable();
OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM [User]", cn);
da.Fill(userTbl);

// 插入一条记录
OleDbConnection cn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\\test.mdb;");
OleDbCommand cmd = new OleDbCommand("INSERT INTO [User] ([ID], [UserName], [UserPassword]) VALUES (1, 'user_ab', '123')", cn);

cn.Open();
cmd.ExecuteNonQuery();
cn.Close();

// 更新
OleDbConnection cn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\\test.mdb;");
OleDbCommand cmd = new OleDbCommand("UPDATE [User] SET [UserPassword]='newpwd' WHERE [UserName]='user_ab'", cn);

cn.Open();
cmd.ExecuteNonQuery();
cn.Close();