【问题标题】:Reusing mysql connection string重用mysql连接字符串
【发布时间】:2021-12-27 19:52:53
【问题描述】:

我正在编写一个 C# windows 应用程序来更新 WordPress 中使用的自定义 MySQL 数据库。我想要做的是将连接字符串放在一个地方。例如,我包含了我准备将所有内容切换到存储生产者的测试代码。我在网上找了一个很好的例子,或者我做错了什么

public void FindURL()
{
    string connStr = "server=127.0.0.1;user=root;database=mypocket;port=3306;password=";
    MySqlConnection conn = new MySqlConnection(connStr);
    conn.Open();
   
    try
    {
        MySqlCommand cmd = new MySqlCommand("select  id, fullname from siteinfo where Site_Url like '%" + txtURLInput.Text + "%'", conn);
        MySqlDataReader reader = cmd.ExecuteReader();

        bool hasRecords = false;
        while (reader.Read())
        {
            
        }

        if (!hasRecords)
        {
            
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show("Error Getting Records" + ex.ToString());
    }
}
public void FindName()
{
    string connStr = "server=127.0.0.1;user=root;database=mypocket;port=3306;password=";
    MySqlConnection conn = new MySqlConnection(connStr);
    conn.Open();
    txtNameOutput.Text = "";
    try
    {
        MySqlCommand cmd = new MySqlCommand("select  id, fullname from siteinfo where fullname like '%" + txtCheckName.Text + "%'", conn);
        MySqlDataReader reader = cmd.ExecuteReader();

        bool hasRecords = false;
        while (reader.Read())
        {
            
        }

        if (!hasRecords)
        {
            txtNameOutput.Text = "Not Found";
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show("Error Getting Records" + ex.ToString());
    }
}

【问题讨论】:

标签: c# mysql


【解决方案1】:

它是一个 .Net Framework 应用程序吗?您确实必须使用配置文件。 打开 App.config 文件并添加连接字符串。示例:

<connectionStrings>  
    <add name="myDatabaseConnection" connectionString="server=localhost;user=root;database=mydatabase;port=3306;password=mypassword;" />   
</connectionStrings> 

然后在您的 C# 代码中,您将能够通过“ConfigurationManager”获取它。示例:

        string connectionString = ConfigurationManager.ConnectionStrings["myDatabaseConnection"].ConnectionString;  

来源:https://www.c-sharpcorner.com/blogs/establish-database-connection-with-mysql-in-c-sharp-through-appconfig

【讨论】:

    猜你喜欢
    • 2014-03-31
    • 2013-12-14
    • 2011-08-31
    • 2014-10-28
    • 1970-01-01
    • 2019-08-14
    • 2011-08-23
    • 2015-01-22
    相关资源
    最近更新 更多