2017-06-21 270 views
-1

嘗試連接到數據庫時,我不斷收到一個問題。數據庫應該允許遠程連接,但由於某種原因,它不允許連接。連接到數據庫錯誤的C#

using MetroFramework; 
using MetroFramework.Forms; 
using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 
using System.Data.SqlClient; 

namespace ###WEBSITE### 
{ 
public partial class Form1 : MetroForm 
{ 
    public Form1() 
    { 
     InitializeComponent(); 
    } 

    private void Form1_Load(object sender, EventArgs e) 
    { 

    } 

    private void metroButton1_Click(object sender, EventArgs e) 
    { 
     SqlConnection con = new SqlConnection("Data Source=###WEBSITE###.com:3306;Initial Catalog=neoncheats_mybb;Integrated Security=True"); 
     con.Open(); 
     SqlCommand cmd = new SqlCommand("select * from mybb_users where username = '" + Username.Text + "' and password = '" + Password.Text + "'", con); 
     SqlDataReader dr; 
     dr = cmd.ExecuteReader(); 
     int count = 0; 
     while (dr.Read()) 
     { 
      count += 1; 
     } 

     if (count == 1) 
     { 
      MessageBox.Show("OK"); 
      Form1 f1 = new Form1(); 
      f1.Close(); 
      Form2 f2 = new Form2(); 
      f2.Show(); 
     } 
     else if (count > 0) 
     { 
      MessageBox.Show("Duplicate username and password"); 
     } 
     else 
     { 
      MessageBox.Show("Username or Password incorrect"); 
     } 

     Password.Clear(); // Clears the password field 
    } 

    private void metroButton2_Click(object sender, EventArgs e) 
    { 
     this.Close(); 
    } 

    private void metroLink1_Click(object sender, EventArgs e) 
    { 
     System.Diagnostics.Process.Start("http://###WEBSITE###.com/Forum/member.php?action=lostpw"); 
    } 
} 
} 

注: 的###網站###實際上並不存在,我刪除了網站的名稱。 這個錯誤來自線31(con.Open();) 我一直在使用一個本地數據庫修整,並與「本地主機」作爲域名

我知道我的連接方法並不完全理想得到了同樣的錯誤以及。我真的需要幫助,因爲我很難過,任何幫助表示讚賞!

+1

你得到什麼錯誤? –

+0

您正嘗試將此用作您的數據源「### WEBSITE ###。com」?實際上,數據源看起來像一個IP。什麼錯誤具體返回? –

+0

我正在使用帶有端口的Web主機將數據導向3306(SQL端口)。這是我的錯誤:https://gyazo.com/ca59ca1f4a423a1ae6db61ef09d48666我試圖連接到直接的IP,我仍然得到相同的錯誤 – Thaisen

回答

0

我認爲你必須添加的用戶ID和密碼..

here連接字符串

+0

我嘗試使用用戶名和密碼,但不幸的是我得到了同樣的錯誤 – Thaisen

+0

集成安全標誌被設置,只要帳戶存在服務器端並有權訪問,他應該沒事。 –

0

而不是使用你-數據源的:3306;,試用數據Your-Datasource,3306;

+0

我試過了,可悲的是它沒有奏效 – Thaisen

0

首先,請務必始終使用「使用」的語句像下面當對象支持IDisposable接口:

using (SqlConnection Conn = new SqlConnection(...)) 
{ 
    Conn.Open(); 
} 

這將確保所有,而在該塊是您所創建的對象妥善處置(包括你的連接,你的數據庫管理員會找到你)。

其次,確保將「數據源」設置爲「服務器」,而將「初始目錄」設置爲數據庫。

「Server = myServerAddress; Database = myDataBase; User Id = myUsername; Password = myPassword;」

參見:https://www.connectionstrings.com/sql-server/

希望這應該可以幫助您連接。