我嘗試使用Ado.Net進行Sql連接。我創建一個ConsoleApplication並從我的數據庫中獲取值Name
和UnitPrice
。執行後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();
}
}
}
您能否提供正確的連接字符串,例如MS SQL Server Managment Studio? – Alexander
添加錯誤信息 –
在谷歌搜索例外,你會發現你的問題。 – mybirthname