连接字符串连接到MySql数据库?

时间:2015-12-13 01:25:42

标签: c# mysql connection-string

我正在尝试将MySql数据库连接到我的表单。通过右键单击我的数据库连接并转到属性,我获得了连接字符串。

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

下面是错误和完整代码的图片。

enter image description here

car.cs class:这里我试图连接到数据库。

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

2 个答案:

答案 0 :(得分:2)

它可能想知道密码;)您的消息框说明:

  

使用密码:否...拒绝访问...

像这样:

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

答案 1 :(得分: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()
{
}