3

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#?

3
  • I think "Database" is called Initial Catalog, but besides that it looks correct Commented May 19, 2022 at 8:14
  • 2
    SqlConnection is for Microsoft SQL Server, but it looks like you've actually got MySQL. You should look into the MySQL drivers available for .NET, e.g. dev.mysql.com/downloads/connector/net Commented May 19, 2022 at 8:15
  • you can validate your connection string on this page connectionstrings.com/mysql-connector-net-mysqlconnection Commented May 19, 2022 at 8:15

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, with MySQL it works. Thank you.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.