俺是菜鸟,打算学用ADO.NET,写了如下代码:
static void Main()
{
SqlConnection con=new SqlConnection("server=.:database=login;uid=sa;pwd=;");
try
{
con.Open();
}
catch(System.Exception e)
{
Console.WriteLine(e.Message);
}
Console.WriteLine("test");
con.Close();
Console.WriteLine("test2");
}结果出错了,错误信息:无效的链接
这是为什么阿
我用sql的查询分析器,同样的连接,为什么却可以阿。
static void Main()
{
SqlConnection con=new SqlConnection("server=.:database=login;uid=sa;pwd=;");
try
{
con.Open();
}
catch(System.Exception e)
{
Console.WriteLine(e.Message);
}
Console.WriteLine("test");
con.Close();
Console.WriteLine("test2");
}结果出错了,错误信息:无效的链接
这是为什么阿
我用sql的查询分析器,同样的连接,为什么却可以阿。
using System;
using System.Data.SqlClient;class FirstExample
{
public static void Main()
{
try
{
// step 1: create a SqlConnection object to connect to the
// SQL Server Northwind database
SqlConnection mySqlConnection =
new SqlConnection(
"server=localhost;database=Northwind;uid=sa;pwd=sa"
); // step 2: create a SqlCommand object
SqlCommand mySqlCommand = mySqlConnection.CreateCommand(); // step 3: set the CommandText property of the SqlCommand object to
// a SQL SELECT statement that retrieves a row from the Customers table
mySqlCommand.CommandText =
"SELECT CustomerID, CompanyName, ContactName, Address " +
"FROM Customers " +
"WHERE CustomerID = 'ALFKI'"; // step 4: open the database connection using the
// Open() method of the SqlConnection object
mySqlConnection.Open(); // step 5: create a SqlDataReader object and call the ExecuteReader()
// method of the SqlCommand object to run the SELECT statement
SqlDataReader mySqlDataReader = mySqlCommand.ExecuteReader(); // step 6: read the row from the SqlDataReader object using
// the Read() method
mySqlDataReader.Read(); // step 7: display the column values
Console.WriteLine("mySqlDataReader[\"CustomerID\"] = " +
mySqlDataReader["CustomerID"]);
Console.WriteLine("mySqlDataReader[\"CompanyName\"] = " +
mySqlDataReader["CompanyName"]);
Console.WriteLine("mySqlDataReader[\"ContactName\"] = " +
mySqlDataReader["ContactName"]);
Console.WriteLine("mySqlDataReader[\"Address\"] = " +
mySqlDataReader["Address"]); // step 8: close the SqlDataReader object using the Close() method
mySqlDataReader.Close(); // step 9: close the SqlConnection object using the Close() method
mySqlConnection.Close();
}
catch (SqlException e)
{
Console.WriteLine("A SqlException was thrown");
Console.WriteLine("Number = " + e.Number);
Console.WriteLine("Message = " + e.Message);
Console.WriteLine("StackTrace:\n" + e.StackTrace);
}
}
}
local应该是localhost
用习惯了(local)的形式
Number = 17
Message = SQL Server 不存在或访问被拒绝。
StackTrace:
at System.Data.SqlClient.ConnectionPool.GetConnection(Boolean& isInTransactio
n)
at System.Data.SqlClient.SqlConnectionPoolManager.GetPooledConnection(SqlConn
ectionString options, Boolean& isInTransaction)
at System.Data.SqlClient.SqlConnection.Open()
at FirstExample.Main() in c:\微软资料\testprogramming\contest\class2.cs:line
30
如果都不可以(好像不太可能啊),你就把你的"server="后面改成你的机器名试试。