1

第一次做数据库编程,所以我只是在Access中做了一个数据库来尝试用它做一些事情。我在桌面上创建的数据库名为“TestDatabase”,我在该数据库中创建的表名为“TestTable”。这是我的代码:

using System;
using System.Data;
using System.Data.SqlClient;

namespace DatabaseTest
{
    class Test
    {
        static void Main(string[] args)
        {
            // I don't know if my connection is correct or not. My access database is on my local desktop though
            string connectionString = "Data Source = (local); Initial Catalog = TestDatabase; Integrated Security = SSPI";
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                SqlDataReader reader = null;
                SqlCommand command = new SqlCommand("SELECT * from TestTable", connection);

                connection.Open();
                try
                {
                    reader = command.ExecuteReader();
                }
                catch (InvalidOperationException e)
                {
                    Console.WriteLine(e.ToString());
                }

                // print all the data in the table
                while (reader.Read())
                {
                    Console.Write(reader[0].ToString() + ", ");
                    Console.Write(reader[1].ToString() + ", ");
                    Console.Write(reader[2].ToString() + ", ");
                    Console.Write(reader[3].ToString() + ", ");
                    Console.WriteLine(reader[4].ToString());
                }
            }
            Console.ReadLine();
        }
    }
}

如果您想知道,这是我的桌子的样子:(只是一个玩具示例)

ID   First Name  Last Name   Age     Friend
1    Leon        Ma          18      Yes
2    Amy         Jane        16      No
3    David       Zhang       20      No
4    Alan        Yue         19      Yes

但是,它不起作用,因为我的控制台上什么也没有出现。我做错什么了。真的需要一些帮助。谢谢。

4

1 回答 1

2

您需要类似以下内容才能连接到 Access DB

conn = new System.Data.OleDb.OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\DbPath\SomeAccessFileName.accdb")

配置文件将像这样设置为标准安全

Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\myFolder\myAccessFile.accdb;
Persist Security Info=False;

参考链接访问连接字符串

在后面的代码中创建连接对象的用法

using System.Data.Odbc;

using(OleDbConnection connection = new OleDbConnection(con))
{
    connection.Open();
    OleDbCommand command = new OleDbCommand("SELECT * from TestTable", connection) 
    using(OleDbDataReader reader = command.ExecuteReader())
    {
         while(reader.Read())
         {
            Console.Write(reader[0].ToString() + ", ");
            Console.Write(reader[1].ToString() + ", ");
            Console.Write(reader[2].ToString() + ", ");
            Console.Write(reader[3].ToString() + ", ");
            Console.WriteLine(reader[4].ToString());
         }
    }
}
于 2016-01-11T16:50:44.200 回答