1.新建Access数据库:
using System.Data.OleDb;
using ADOX;
namespace Stainless_steel_PHESel
{
public partial class Prop_SP:Form
{
//获取当前路径
string currentDirectory=Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
string CreatFilePath=Path.Combine(userDefinedDirectory,"新建数据库.mdb");
string strKey="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=CreatFilePath";
//查询路径中是否已经有该表
if(File.Exists(CreatFilePath))
{
//如果有此文件就更新数据库文件
}
else//创建数据库
{
ADOX.Catalog catalog=new Catalog();
catalog.Creat(strKey);//在已知路径里面创建数据库;
catalog.ActiveConnection.Close();
//和新建的数据库建立连接
ADODB.Connection cn=new ADODB.Connection();
cn.Open(strKey);
catalog.ActiveConnection=cn;
//在数据库中添加新表
ADOX.Table table=new ADOX.Table();
table.Name="营业额流水";//表名称
table.Columns.Append("年份",DataTypeEnum.adLongVarWChar,100);//表中的“年份”列;
table.Column.Append("流水明细",DataTypeEnum.adLongVarWChar,100);//表中的“流水明细”列;
cn.Close();
}
}
}
2.在数据库中添加数据:
OleDbConnection conn=new OleDbConnection(strKey);
conn.Open();
OleDbCommand command=new OleDbCommand();
string str="INSERT INTO [营业额流水](年份,流水明细)VALUES("2023","300$")";
command=new OleDbCommand(str,conn);
command.ExecuteNonQuery();
conn.Close();
3.在数据库中删除数据:
string str="DELETE FROM [营业额流水] WHERE [年份]=2023";
OleDbCommand command=new OleDbCommand(str,conn);
command.ExecuteNonQuery();
conn.Close();
conn.Dispose();
4.更新数据库:
string strUpdateInformation="[年份]=2024,[流水明细]=5000¥";
string str=$"UPDATE [营业额流水] SET {strUpdateInformation} WHERE [年份]=2023";
OleDbCommand command=new OleDbCommand(str,conn);
command.ExecuteNonQuery();
conn.Close();
conn.Dispose();
5.查询数据库:
string str="SELECT * FROM [营业额流水] WHERE [年份]=2023 and [流水明细]=300$ ORDER BY [年份]";
OleDbDataAdapter ODDA=new OleDbDataAdapter(str,conn);
DataTable DT=new DataTable();
ODDA.Fill(DT);//此时DT里面有两列,分别为年份和流水明细,且年份都是2023年的,流水明细都是300$;
conn.Close();
6.查找数据库中某列中为某值的行数有多少
//查找数据库中年份为2023的数据有多少行
string str="Select count(*) from [营业额流水] Where [年份]=2023";
OleDbCommand command=new OleDbCommand(str,conn);
int count=Convert.ToInt32(command.ExecuteScalar());//count 即为要查找的总行数;
conn.Close();
conn.Dispose();