2023年11月23日发(作者:)

C#连接ACCESS数据库的详细步骤!

⼀、建⽴FORM窗体,加⼀个按钮控件,加⼀个DATAGRIDVIEW控件。

⼆、双击FORM,加⼊命名空间using ;

双击按钮,进⼊按钮代码,写如下代码

OleDbConnection strConnection = new OleDbConnection("Provider=.4.0;Data Source=" + "员⼯信息.mdb" +

";Persist Security Info=False");

//建⽴数据库引擎连接,注意数据表(后缀为.db)应放在DEBUG⽂件下

OleDbDataAdapter myda = new OleDbDataAdapter("select * from 雇员 ,strConnection);

//建⽴适配器,通过SQL语句去搜索数据库

DataSet myds = new DataSet();

//建⽴数据集

(myds, "雇员");

//FILL的⽅式将适配器已经连接好的数据表填充到数据集MYDS这张表

urce = ["联系⼈ID"];

//⽤显⽰控件来显⽰表

三、按F5运⾏后,点击BUTTON按钮,便会显⽰相应的SQL语句下的数据库⾥的表。

下⾯利⽤Commandreader对象在控制台应⽤程序下输出数据。

[csharp]

01. using System;

02. using c;

03. using ;

04. using ;

05. using ;

06.

07. namespace ConsoleApplication19

08. {

09. class Program

10. {

11. static void Main(string[] args)

12. {

13.

14. OleDbConnection mycon =null;

15. OleDbDataReader myReader=null;

16. try

17. {

18. string strcon = "Provider=.4.0;Data Source=;";

19. mycon = new OleDbConnection(strcon);

20. ();

21. string sql = "select * from 雇员 ";

22. OleDbCommand mycom = new OleDbCommand(sql, mycon);

23. myReader = eReader();

24. while (())

25. {

26. ine(ing(0)+" "+ble(1)+" "+ing(2)+

27.

28. }

29.

30. }

31. finally

32. {

33. ();

34. ();

35.

36. }

37. }

38. }

39. }

今天⼀个⽹友问到如何在C#中连接access数据库,经查找资料以及请教⽹友sammyLan,终于测试成功,⼤致过程如下

1、建⽴⼀个access数据库名字为,⾥⾯有⼀个表person,它有两个字段personname(备注:由于nameaccess的关键字之⼀,所以尽量

1、建⽴⼀个access数据库名字为,⾥⾯有⼀个表person,它有两个字段personname(备注:由于nameaccess的关键字之⼀,所以尽量

不要将字段名或者表明起为name,否则可能出错)age,分别是⽂本和数字类型。

并插⼊两条记录,如下所⽰

personname age

bushi 30

John 20

2、将access数据库⽂件所在的⽬录(假设名为access)设为共享,假设我的机器地址为192.168.1.10,那么设为共享后,在地址栏内输

⼊这个⽬录应该之后可以看到⽂件。

3、打开VS2008,菜单中点"新建"->"项⽬"->"Visual C#"->"Windows"->"windows窗体应⽤程序",建⽴⼀个新的C#窗体程序。

4、修改代码⽂件的内容,其完整C#代码如下。已经加了注释,就不再另外解释了

[c-sharp]

01. using ;

02. using ;

03. using ;

04.

05. namespace WindowsFormsApplication1

06. {

07. static class Program

08. {

09. ///

10. /// 应⽤程序的主⼊⼝点。

11. ///

12. [STAThread]

13. static void Main()

14. {

15. //构造连接字符串

16. string strConnection="Provider=.4.0;";

17. strConnection +=@"Data Source=//192.168.1.10//access//";

18.

19.

20. OleDbConnection objConnection = new OleDbConnection(strConnection);

21. (); //打开连接

22. OleDbCommand sqlcmd = new OleDbCommand(@"select * from person where personname='John'"

23. OleDbDataReader reader = eReader(); //执⾏查

24. int age = new int();

25. if(()){ //这个read调⽤很重要!不写的话运⾏时将提⽰找不到

26. age = (int)reader["age"]; //取得字段的值

27. ();

28. ();

29. }

30.

31. VisualStyles();

32. patibleTextRenderingDefault(false);

33. Form1 form = new Form1();

34. = ng();

35. (form);

36. }

37. }

38. }

建⽴连接

语句

数据