简体   繁体   English

在本地主机上连接到MySQL失败

[英]Failure connecting to MySQL on localhost

So I'm trying to add a new record to a SQL Database. 因此,我正在尝试向SQL数据库添加新记录。 The MySQL database server is running on XAMPP, and I've configured the username to be root and the password to be test. MySQL数据库服务器在XAMPP上运行,并且我已经将用户名配置为root,密码配置为test。 I've tried both 'localhost' and '127.0.0.1' as the server addresses but they both don't work. 我已经尝试使用“ localhost”和“ 127.0.0.1”作为服务器地址,但是它们都无法正常工作。 This is using: 这正在使用:

using System;
using System.Data;
using Gtk;
using MySql.Data;
using MySql.Data.MySqlClient;

When the button is clicked, it catches the exception and displays an error message, but I can't figure out why the connection to the server fails. 单击该按钮时,它会捕获异常并显示错误消息,但是我无法弄清楚为什么与服务器的连接失败。

protected void OnAddItemClicked(object sender, EventArgs e)
{
    MySqlConnection connection;
    string server = "localhost";
    string database = "shop";
    string uid = "root";
    string password = "test";
    string connectionString;
    connectionString = "SERVER=" + server + ";" + "DATABASE=" +
    database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";

    connection = new MySqlConnection(connectionString);

    try
    {
        connection.Open();
        if (connection.State == ConnectionState.Open)
        {
            MySqlCommand cmd = new MySqlCommand("INSERT INTO items (ItemName,Price,PriceVAT) values(@ItemName,@Price,@PriceVAT", connection);
            cmd.Parameters.Add("@ItemName", nameEntry.Text);
            cmd.Parameters.Add("@Price", priceEntry.Text);
            cmd.Parameters.Add("@PriceVAT", "1");
            cmd.ExecuteNonQuery();

            MessageDialog md = new MessageDialog(null, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, "Data entered successfully.");
            md.Run();
            md.Destroy();
        }
        else
        {
            MessageDialog md = new MessageDialog(null, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, "Database connection failed.");
            md.Run();
            md.Destroy();
        }

    }
    catch (Exception ex)
    {
        MessageDialog md = new MessageDialog(null, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, "Error occurred, please try again later");
        md.Run();
        md.Destroy();
    }

    connection.Close();
}

If db user and password correct then ake your connection string like 如果数据库用户和密码正确,则使用如下连接字符串

connectionString  = @"server=" + server  + ";userid=" + uid + ";password="
                       + password + ";database=" + database;

and if your mysql port is not default like 3306 then you can specify your custom port number too like 如果您的mysql端口不是默认端口,例如3306那么您也可以指定自定义端口号,例如

connectionString = @"server=" + server + ";port=" + port + ";userid=" + uid  + ";password="
                       + password  + ";database=" + database;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM