Home > front end >  C# SQL Connection not found
C# SQL Connection not found

Time:05-20

How can I connect a SQL database in C#?

My code:

const string connectionString = "Data Source=127.0.0.1;User ID=root;Database=MyDatabase;Password=MyPassword";
var conn = new SqlConnection(connectionString);
conn.Open();
conn.Close();

I get: Error: 40 - could not open a connection to sql server. I tried also in Python and it worked well:

cnx = mysql.connector.connect(user='root', password='MyPassword', host='127.0.0.1', database='MyDatabase')
cursor = cnx.cursor()

What am I missing in C#?

CodePudding user response:

Please use MySqlConnection for MySql DB.

            const string connectionString = "Data Source=127.0.0.1;User ID=root;Database=MyDatabase;Password=MyPassword";         
            MySqlConnection conn = new MySqlConnection(connectionString );
            conn.Open();

            string sqlcommand = "SELECT Query";
            MySqlCommand cmd = new MySqlCommand(sqlcommand , conn);

CodePudding user response:

please follow this example

using MySql.Data.MySqlClient;

var connectionString = "server=serveradress;database=dbName;user id=sqluser;password=abc;";

using (var connection = new MySqlConnection(connectionString))
{
    connection.Open();
    
    using var command = new MySqlCommand("SELECT COUNT(*) FROM tableName ", connection);
    var Count = command.ExecuteScalar();

    Console.WriteLine($"There are {Count } movies");
}

server adress in general is 127.0.0.1 ,if you are working locally

here the source page : example and also consider reading this page here docs

  • Related