rr944276
rr944276

Reputation: 57

Reusing mysql connection string

I am writing a C# windows application to update a custom MySQL database used in WordPress. what I am trying to do is to have the connection string in one place. for example, I included the test code I am preparing to switch everything to stored producers. I looked online and can not find a good example or I am doing something wrong

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());
    }
}

Upvotes: 0

Views: 92

Answers (1)

ragnar
ragnar

Reputation: 190

is it a .Net Framework application? You must indeed use config file. Open your App.config file and add your connection string. Example:

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

Then in your C# code you will be able to get it via the "ConfigurationManager". Example:

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

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

Upvotes: 1

Related Questions