2014-02-23 53 views
-6

連接到SQL Server數據庫中,我曾嘗試與下面的代碼:無法從代碼

private void button2_Click(object sender, EventArgs e) 
{ 
    string connString = @"Server=localhost;Initial Catalog=Database2;User id=***;Password=***;"; 

    SqlConnection sqlConn = new SqlConnection(connString); 

    string sqlQuery = @"SELECT * from tableP"; 
    SqlCommand cmd = new SqlCommand(sqlQuery, sqlConn); 

    SqlDataAdapter da = new SqlDataAdapter(cmd); 
    DataTable table = new DataTable(); 
    da.Fill(table); 

    DataGridView dgv = new DataGridView(); 
    dgv.DataSource = new BindingSource(table, null); 
} 

其他信息:

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)

+3

你甚至不問一個問題,你剛纔向我們扔代碼,並希望我們解決這個問題。 –

+1

親愛的請不要將您的憑證暴露給外界。我已經編輯它。 –

+0

嗨,你可以嘗試與其他連接字符串與SQLServer在https://www.connectionstrings.com/sql-server-2008/ –

回答

2

您需要先對數據庫進行任何操作前打開連接。

sqlConn.Open(); 

和與此相關的字符串

connectionString="Data Source=localhost;Initial Catalog=Database2; User ID=myUsername;Password=myPassword;" 
+0

我仍然得到ssame錯誤。 – user3342777

+0

@ user3342777:你得到哪個錯誤? –

+0

附加信息:建立到SQL Server的連接時發生網絡相關或實例特定的錯誤。服務器未找到或無法訪問。驗證實例名稱是否正確,並將SQL Server配置爲允許遠程連接。 (提供程序:命名管道提供程序,錯誤:40 - 無法打開與SQL Server的連接) – user3342777

0

試試這個

private void button2_Click(object sender, EventArgs e) 
{ 
     string connString = 'yourconnectionstring' 
     SqlConnection sqlConn = new SqlConnection(connString); 
    try 
    { 

     sqlConn.Open(); 
     string sqlQuery = @"SELECT * from tableP"; 
     SqlCommand cmd = new SqlCommand(sqlQuery, sqlConn); 
     SqlDataAdapter da = new SqlDataAdapter(cmd); 
     DataTable table = new DataTable(); 
     da.Fill(table); 
     DataGridView dgv = new DataGridView(); 
     dgv.DataSource = new BindingSource(table, null); 
    } 
    catch (Exception) 
    { 

     SqlConn.Close(); 
    } 
    finally 
    { 
     SqlConn.Close(); 
    } 
} 
+0

現在它確定heheeheh – Developerzzz

+0

它仍然無法正常工作。 – user3342777