2011-06-08 94 views
1

我似乎无法连接到我的本地数据库。 每次运行它,它都会弹出一个空白窗口(空白命令行窗口)。C#和SQL Server连接

我错过了什么?

using System; 
using System.Collections.Generic; 
using System.Text; 
using System.Data.SqlClient; 

namespace dbtest1 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      string myConnectionString = "Initial Catalog=myDB;Data Source=localhost;Integrated Security=SSPI;"; 
      SqlConnection myConnection = new SqlConnection(myConnectionString); 
      string myInsertQuery = "INSERT INTO tts (min, max, average, lh, stdev, main_id) Values(5,5,5,'ASU',5,55)"; 
      SqlCommand myCommand = new SqlCommand(myInsertQuery); 
      myCommand.Connection = myConnection; 
      myConnection.Open(); 
      myCommand.ExecuteNonQuery(); 
      myCommand.Connection.Close(); 
     } 
    } 
} 

当我运行调试它给我的错误在myConnection.Open();

SqlException was unhandled: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)

+1

你是不是实际上将任何内容输出到控制台窗口,这就是为什么它是空白的。你得到什么实际的错误? – 2011-06-08 22:48:41

+0

当我运行调试它给我在myConnection.Open();错误; SqlException未处理:与SQL Server建立连接时发生网络相关或特定于实例的错误。服务器未找到或无法访问。验证实例名称是否正确,并将SQL Server配置为允许远程连接。 (提供程序:命名管道提供程序,错误:40 - 无法打开与SQL Server的连接) – 2011-06-09 14:29:55

回答

3

你的SQL服务器未配置,谈谈TCP/IP(这是什么localhost暗示)

您可以更改连接字符串使用(local)代替localhost(注:括号内是很重要的。)像这样的:

Data Source=(local); 

您可以将您的SQL Server配置为接受TCP/IP连接。

打开了SQL服务器Confuguration经理并导航到SQL Server网络配置 - >协议

在右边你会看到的协议,如共享内存,命名管道,TCP名单/ IP等。确保TCP/IP已打开。 (点击右键并选择“启用”)

你提到的其他地方使用的是SQL Server Express的,在这种情况下,您的数据源还必须包括实例名称SQLEXPRESS,就像这样:

Data Source=localhost\SQLEXPRESS 
+0

它的作品!谢谢 – 2011-06-15 17:25:12

+0

@JohnRyann请指出哪些建议有效,第一或第二 – flexxxit 2013-05-20 10:09:00

1

我敢打赌,应用程序是否运行。你是否检查过数据库以查看是否插入了值?

空白命令行窗口很可能是因为您已将项目类型设置为Windows控制台项目。

也许在Main方法的末尾添加一个Console.WriteLine("No worries!");

+3

在此之后使用'Console.ReadKey();',因此控制台不会立即消失。 – 2011-06-08 22:51:24

+0

我检查了数据库,并没有新的记录插入。该应用程序不起作用,显然有些东西是不正确的。弹出的窗口不会消失。它停留在那里。它实际上发生在myConnection.Open()。 – 2011-06-09 14:28:41

+0

我实际上使用的是SQL Server精简版(sqlexpress) – 2011-06-09 14:49:59