2015-12-13 184 views
0

我想連接MySql數據庫到我的窗體。我得到了連接字符串,我右鍵單擊我的數據庫連接並轉到屬性。連接字符串連接到MySql數據庫?

connection.ConnectionString = "server=localhost;user id=root;database=island_dealership;"+ 
     "persistsecurityinfo=True;allowuservariables=True"; 

下面是錯誤和完整代碼的圖像。

enter image description here

car.cs類:在這裏我試圖連接到數據庫。

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 MySql.Data.MySqlClient; 

namespace DatabaseProject 
{ 
    public partial class Car : Form 
    { 
     MySqlConnection connection = new MySqlConnection(); 
     MySqlConnection cmd; 
     public Car() 
     { 
      InitializeComponent(); 
     } 

     private void Form1_Load(object sender, EventArgs e) 
     { 
      try 
      { 
       connection.ConnectionString = "server=localhost;user id=root;database=island_dealership;persistsecurityinfo=True;allowuservariables=True";//Connection String.... 
       connection.Open(); 
       MessageBox.Show("Connected to MySql database"); 
      } 
      catch(Exception e1) 
      { 
       MessageBox.Show("Connection failed Due to " + e1.ToString()); 
      } 

     } 

     private void submitCar_Click(object sender, EventArgs e) 
     { 

     } 
    } 
} 

enter image description here

+0

你不指定密碼。 [http://www.connectionstrings.com/mysql/](http://www.connectionstrings.com/mysql/) – MickyD

+0

連接字符串缺少密碼。你必須添加密碼。它應該是這樣的一些東西:「數據源=服務器名稱\實例名稱;初始目錄=數據庫名稱;用戶名= SQLLoginName;密碼= SQLLoginPassword; –

+0

不要使用'root'用戶 –

回答

2

它可能會想知道密碼;)你的消息框是這麼說的:

使用密碼:NO ...訪問被拒絕......

像這樣:

server=localhost;uid=root;pwd=YOURPASSWORDHERE;database=YOURDATABASENAMEHERE; 
0

這裏使用下面的代碼或參照本link

private MySqlConnection connection; 
private string server; 
private string database; 
private string uid; 
private string password; 

//Constructor 
public DBConnect() 
{ 
    Initialize(); 
} 

//Initialize values 
private void Initialize() 
{ 
    server = "localhost"; 
    database = "connectcsharptomysql"; 
    uid = "username"; 
    password = "password"; 
    string connectionString; 
    connectionString = "SERVER=" + server + ";" + "DATABASE=" + 
    database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";"; 

    connection = new MySqlConnection(connectionString); 
} 

//open connection to database 
private bool OpenConnection() 
{ 
} 

//Close connection 
private bool CloseConnection() 
{ 
} 

//Insert statement 
public void Insert() 
{ 
} 

//Update statement 
public void Update() 
{ 
} 

//Delete statement 
public void Delete() 
{ 
} 

//Select statement 
public List <string> [] Select() 
{ 
} 

//Count statement 
public int Count() 
{ 
} 

//Backup 
public void Backup() 
{ 
} 

//Restore 
public void Restore() 
{ 
} 
+0

[link](https:// www .codeproject.com /用品/ 43438 /連接-C到MySQL) –