数据结构
代码
using System;
using System.Data;
using System.Data.OleDb;
namespace ACCESS数据库
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("ACCESS数据库");
DbAccess dbAccess = new DbAccess();
dbAccess.select();
dbAccess.insert();
dbAccess.select();
dbAccess.update();
dbAccess.select();
dbAccess.delete();
dbAccess.select();
Console.ReadLine();
}
}
class DbAccess
{
OleDbConnection oleDb = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\projects\实体关系映射框架\实体关系映射框架\bin\Debug\数据库1.mdb");
int id = 0;
public DbAccess()
{
oleDb.Open();
deleteAll();
init();
}
~DbAccess()
{
oleDb.Close();
}
public void insert()
{
Console.WriteLine("-----insert----------------------------------------");
string sql = "insert into tb (myName) values ('name-insert')";
OleDbCommand oleDbCommand = new OleDbCommand(sql, oleDb);
int id = oleDbCommand.ExecuteNonQuery();
}
public void delete()
{
Console.WriteLine("-----delete----------------------------------------");
string sql = "delete from tb where myName='name-up'";
OleDbCommand oleDbCommand = new OleDbCommand(sql, oleDb);
int i = oleDbCommand.ExecuteNonQuery();
}
public void update()
{
Console.WriteLine("-----update----------------------------------------");
string sql = "update tb set myName='name-up' where myName='name-insert'";
OleDbCommand oleDbCommand = new OleDbCommand(sql, oleDb);
int i = oleDbCommand.ExecuteNonQuery();
}
public void select()
{
string sql = "select * from tb";
//获取表1中昵称为LanQ的内容
OleDbDataAdapter dbDataAdapter = new OleDbDataAdapter(sql, oleDb); //创建适配对象
DataTable dt = new DataTable(); //新建表对象
dbDataAdapter.Fill(dt); //用适配对象填充表对象
foreach (DataRow item in dt.Rows)
{
Console.WriteLine(item[0] + " | " + item[1]);
}
}
public void deleteAll()
{
string sql = "delete from tb where 1=1";
OleDbCommand oleDbCommand = new OleDbCommand(sql, oleDb);
int i = oleDbCommand.ExecuteNonQuery();
}
private void init()
{
for(int i = 0; i < 3; i++)
{
string sql = "insert into tb (myName) values ('name"+ i + "')";
OleDbCommand oleDbCommand = new OleDbCommand(sql, oleDb);
oleDbCommand.ExecuteNonQuery();
}
}
}
}
运行效果
参考资料