简体   繁体   English

将C#连接到MYSQL数据库?

[英]Connecting C# to MYSQL database?

So i been trying to connect C# windows from to MYSQL database, i tryed many different methods that i found online but none seems to be working. 因此,我一直试图将C#Windows从中连接到MYSQL数据库,我尝试了许多我在网上找到的不同方法,但似乎都没有用。 here is my code please help (keep in mind this is the first time i use database before). 这是我的代码,请帮助(请记住,这是我第一次使用数据库)。

Here is the connecting class 这是连接课程

class DbConnect
{
    public static void DBConnect()
    {
        string connstr = 
        "server=localhost;user=root;database=login;port=3306;password=Password";

        MySqlConnection conn = new MySqlConnection(connstr);

        try
        {
            conn.Open();
        }
        catch
        {
            Console.WriteLine("went rong");
        }
    }

}

Here is the windows form im using 这是我正在使用的Windows表格

private void btnenter_Click(object sender, EventArgs e)
 {
      DbConnect.DBConnect();
      MySqlCommand query = new MySqlCommand("INSERT INTO logininfo (username, 
      password) VALUES(@username, @password");
        try
        {
            query.Parameters.AddWithValue("@username", txtusername.Text);
            query.ExecuteNonQuery();
            MessageBox.Show("S");
        }

        catch (Exception )
        {
            MessageBox.Show("something went wrong");
        }
        finally
        {
            DbConnect.DBClose();
        }

    }

User is passed in MySQL connection string using Uid . 使用Uid在MySQL连接字符串中传递用户。 So your connection string should be like: 因此,您的连接字符串应类似于:

"server=localhost;Uid=root;database=login;port=3306;password=tro63jans";

You may see: MySQL connection string. 您可能会看到: MySQL连接字符串。

You should also catch exception in some object, so that you can get the details about the exception. 您还应该在某个对象中捕获异常,以便获得有关异常的详细信息。 Currently you are not showing any useful message from your exception. 当前,您没有从异常中显示任何有用的消息。

catch (Exception ex) //at least
{
    MessageBox.Show("something went wrong: " + ex.ToString());
}

One problem you have here is you're not setting the Connection property of your MysqlCommand to the MySqlConnection you're making earlier. 您这里遇到的一个问题是您没有将MysqlCommand的Connection属性设置为您之前创建的MySqlConnection。

  1. Change DBConnect() to return your MySqlConnection. 更改DBConnect()以返回您的MySqlConnection。
  2. Set your MySqlCommand's Connection property to the returned value. 将MySqlCommand的Connection属性设置为返回值。

PSEUDO-CODE 伪代码

MySqlConnection conn = DBConnect.DBConnect();
 MySqlCommand command = new MySqlCommand(commandStr, conn);
command.ExecuteNonQuery();
conn.Close();

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

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