Sol Sol - 8 months ago 38
SQL Question

How to verify that you are connected to a MySQL database in C#?

I added the reference for the MySQL server in C#. I thought I have this code right. I know the connection values are right for testing. Here is my error:

{"A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)"}

My WPF text boxes and Buttons:

<TextBox x:Name="textError" HorizontalAlignment="Left" Height="35" Margin="125,39,0,0" TextWrapping="Wrap" Text="If Error this will show it" VerticalAlignment="Top" Width="240"/>
<TextBox x:Name="textUser" HorizontalAlignment="Left" Height="23" Margin="125,118,0,0" TextWrapping="Wrap" Text="Username" VerticalAlignment="Top" Width="120"/>
<TextBox x:Name="textPassword" HorizontalAlignment="Left" Height="23" Margin="125,168,0,0" TextWrapping="Wrap" Text="Password" VerticalAlignment="Top" Width="120"/>

My C# code:

namespace namespace1
public partial class MainWindow : Window
public MainWindow()

private MySqlConnection connection;
private string server;
private string database;
private string uid;
private string password;

private void button_Click(object sender, RoutedEventArgs e)
if (textUser.Text != "" & textPassword.Text != "")
server = "localhost";
database = "test";
uid = "username";
password = "password";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
string queryText = @"SELECT Count(*) FROM Table1
WHERE username = @Username AND password = @Password";

using (SqlConnection cn = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand(queryText, cn))
cmd.Parameters.AddWithValue("@Username", textUser.Text);
cmd.Parameters.AddWithValue("@Password", textPassword.Text);
int result = (int)cmd.ExecuteScalar();
if (result > 0)
MessageBox.Show("Logged In!");
MessageBox.Show("User Not Found!");


Use the appropriate MySQL classes.

using MySql.Data.MySqlClient;

string connString = @"server=localhost;userid=drew;password=OpenSesame;database=stackoverflow";


        long lRet = 0;
        using (MySqlConnection lconn = new MySqlConnection(connString))
            using (MySqlCommand cmd = new MySqlCommand())
                cmd.Connection = lconn;
                cmd.CommandText = @"select count(*) as theCount from batchQMetricsToUpdate where status=1";
                lRet = (long)cmd.ExecuteScalar();

Add References screenshot:

enter image description here