一、连接access数据库
连接数据库:工具---连接到数据库
复制粘贴路径备用。
using System;
using System.Collections.Generic;
using System.Data; //操作数据表
using System.Data.OleDb; //连接access excel
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace database
{
internal class Program
{
static void Main(string[] args)
{
Access access = new Access();
access.Find();
Console.ReadKey();
access.Add();
Console.WriteLine("回车继续");
Console.ReadKey();
access.Del();
Console.WriteLine("回车继续");
Console.ReadKey();
access.Change();
Console.WriteLine("回车继续");
Console.ReadKey();
access.Get();
}
}
//连接数据库
class Access
{
OleDbConnection oleDb = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\vs\test.mdb"); //需要new一个人
public Access()
{
oleDb.Open(); //利用oleDb中的组件open函数打开数据库
}
public void Get() //获取数据
{
string sql = "select * from student"; //从student里选取所有内容,*表示所有
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] + "|" + item[2] + "|" + item[3]);
}
}
public void Find() //获取表中姓名是小明的内容
{
string sql = "select * from student WHERE 姓名='小明'";
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] + "|" + item[2] + "|" + item[3]);
}
}
public bool Add() //往表中添加一条记录
{
string sql = "insert into student (姓名,年龄,学号) values ('小高','13','250')";
OleDbCommand oleDbCommand = new OleDbCommand(sql, oleDb);
int i = oleDbCommand.ExecuteNonQuery(); //返回被修改的数目
return i > 0;
}
public bool Del() //删除姓名是小红的记录
{
string sql = "delete from student where 姓名='小红'";
OleDbCommand oleDbCommand = new OleDbCommand(sql, oleDb);
int i = oleDbCommand.ExecuteNonQuery();
return i > 0;
}
public bool Change() //将表student中姓名为小东的学号号修改成222
{
string sql = "update student set 学号='222' where 姓名='小东'";
OleDbCommand oleDbCommand = new OleDbCommand(sql, oleDb);
int i = oleDbCommand.ExecuteNonQuery();
return i > 0;
}
}
}
Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\vs\test.mdb
常见问题
1.未经处理的异常System.InvalidOperationException:“The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine.”
项目名称→右键“属性”→生成→目标平台→将“Any CPU”改为“x64”
2.错误CS1069未能在命名空间“System.Data.OleDb”中找到类型名“OleDbConnection”。
项目——管理Nuget程序包——搜索下载
二、DataTable操作
三、C#其他小操作
注释/// <summary>
public class TestTwo : MonoBehaviour
{
/// <summary>
/// This is Function 1
/// </summary>
public static void Function1()
{
}
// This is Function 2
public static void Function2()
{
}
}
鼠标放在调用的Function1和Function2函数时,Function1直接显示了注释说明,Function2则什么也没有,需按F12进入函数查看注释。若需要两行注释,如下
/// <summary>
/// <para>This is Function1.1</para>
/// <para>This is Function1.2</para>
/// </summary>
public static void Function1()
{
}