2016-01-11 49 views
1

第一次進行數據庫編程,所以我只是在Access中創建了一個數據庫來嘗試使用它進行操作。我創建的數據庫在我的桌面上名爲「TestDatabase」,我在這個數據庫中創建的表名爲「TestTable」。這裏是我的代碼:嘗試連接到Access數據庫表以檢索數據,但遇到困難

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 

但是,這是行不通的,因爲沒有出現在我的控制檯。我做錯了什麼。真的需要一些幫助。謝謝。

+0

您是否有在本地主機上運行的SQL Server(或其他數據庫)實例?通常使用「數據源=(本地)」。 Access通常加載類似於「Provider = Microsoft.ACE.OLEDB.12.0; data source = C:\\ filename.accdb」的東西。 –

+0

是否有你爲什麼使用Access而不是像mysql這樣的原因? –

+0

@devlincarnate你的問題是基於你的評論意見不是每個人都使用相同的'DBMS' – MethodMan

回答

2

你需要像下面這個連接到Access數據庫

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; 

參考鏈接Access connection strings

用途用於創建代碼背後的連接對象

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()); 
     } 
    } 
} 
相關問題