2016-12-01 88 views
0

我嘗試使用Ado.Net進行Sql連接。我創建一個ConsoleApplication並從我的數據庫中獲取值NameUnitPrice。執行後Console表示無法打開連接。我犯了什麼錯誤?Ado.net Sql連接

這裏是我的代碼:

using System; 
using System.Collections.Generic; 
using System.Data.SqlClient; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 

class ConsoleApplication1 
{ 
    static void Main() 
    { 
     string connectionString = 
      "Data Source=EMINCIFTCI/EMIN;Initial Catalog=Ado;User ID=sa;Password=10203040"; 


     string queryString = 
      "SELECT Name, UnitPrice from dbo.Product " 
       + "ORDER BY UnitPrice DESC;"; 

     using (SqlConnection connection = 
      new SqlConnection(connectionString)) 
     { 

      SqlCommand command = new SqlCommand(queryString, connection); 

      try 
      { 
       connection.Open(); 
       SqlDataReader reader = command.ExecuteReader(); 
       while (reader.Read()) 
       { 
        Console.WriteLine("\t{0}\t{1}", 
         reader[0], reader[1]); 
       } 
       reader.Close(); 
      } 
      catch (Exception ex) 
      { 
       Console.WriteLine(ex.Message); 
      } 
      Console.ReadLine(); 
     } 
    } 
} 

My Database

+0

您能否提供正確的連接字符串,例如MS SQL Server Managment Studio? – Alexander

+0

添加錯誤信息 –

+0

在谷歌搜索例外,你會發現你的問題。 – mybirthname

回答

3

假設EMINCIFTCI/EMIN是您的計算機名和(我認爲)SQL Server實例,你需要用一個反斜槓換正斜槓(二,從技術上講,除非你使用逐字字符串)。

因此,使用

string connectionString = 
      "Data Source=EMINCIFTCI\\EMIN;Initial Catalog=Ado;User ID=sa;Password=10203040"; 

string connectionString = 
      @"Data Source=EMINCIFTCI\EMIN;Initial Catalog=Ado;User ID=sa;Password=10203040"; 

您可以查看https://www.connectionstrings.com/

+0

感謝您的幫助。我對數據源犯了一個錯誤。它正在工作 –

0

我想連接字符串應該是正確的"Data Source=EMINCIFTCI/EMIN;Initial Catalog=Ado;User ID=sa;Password=10203040;"

應該有分號到底