现在的位置: 首页 > 综合 > 正文

C# 连接ACCESS数据库代码实例

2013年07月15日 ⁄ 综合 ⁄ 共 1847字 ⁄ 字号 评论关闭

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

1、建立一个access数据库名字为CSharptest.mdb,里面有一个表person,它有两个字段personname(备注:由于name是access的关键字之一,所以尽量不要将字段名或者表明起为name,否则可能出错)和age,分别是文本和数字类型。

并插入两条记录,如下所示

personname     age

bushi                   30

John                    20

2、将access数据库文件CSharptest.mdb所在的目录(假设名为access)设为共享,假设我的机器地址为192.168.1.10,那么设为共享后,在地址栏内输入\\192.168.1.10\access\这个目录应该之后可以看到CSharptest.mdb文件。

3、打开VS2008,菜单中点"新建"->"项目"->"Visual C#"->"Windows"->"windows窗体应用程序",建立一个新的C#窗体程序。

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

view plaincopy to clipboardprint?
using System.Windows.Forms;  
using System.Data;  
using System.Data.OleDb;  
 
namespace WindowsFormsApplication1  
{  
    static class Program  
    {  
        /// <summary>  
        /// 应用程序的主入口点。  
        /// </summary>  
        [STAThread]  
        static void Main()  
        {  
            //构造连接字符串  
           string strConnection="Provider=Microsoft.Jet.OleDb.4.0;";  
         strConnection +=@"Data Source=\\192.168.1.10\\access\\CSharptest.mdb";  
 
 
            OleDbConnection objConnection = new OleDbConnection(strConnection);  //建立连接  
            objConnection.Open();  //打开连接  
            OleDbCommand sqlcmd = new OleDbCommand(@"select * from person where personname='John'",objConnection);  //sql语句  
            OleDbDataReader reader = sqlcmd.ExecuteReader();              //执行查询  
            int age = new int();  
           if(reader.Read()){ //这个read调用很重要!不写的话运行时将提示找不到数据  
                age = (int)reader["age"];   //取得字段的值  
                objConnection.Close();  
                reader.Close();  
            }  
 
            Application.EnableVisualStyles();  
            Application.SetCompatibleTextRenderingDefault(false);  
            Form1 form = new Form1();  
            form.Text = age.ToString();  
            Application.Run(form);  
        }  
    }  

 

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/laomai/archive/2009/04/27/4131008.aspx

【上篇】
【下篇】

抱歉!评论已关闭.