Hi I'm trying to connect to a database using System.Data.SqlClient. I think I have everything correct, but for some reason Visual Studio gives out an error:
EDIT: It turns out I was dumb and using System.Data.SqlClient when my database is MySql so I changed it to MySql.Data.MySqlClient and changed all the variables methods and everything. I also changed the port that It was using to 3306 cause it's the port I have set for mysql in xampp. Although I still get an error that says:
System.ArgumentException: „Connection option 'server' is duplicated.”
Now to answer some more questions, I don't know what is the name of the instance but I never set any so Idk if there is one or not(Sorry I'm not very advanced). I didn't add a password to the connection string cause the only user I have is root without any password. I think I seen some people used something like TrusedConnection=true or something but I don't know if it's the right thing to do here. My MySql version is 15.1. Here is the updated code:
using System;
using MySql.Data.MySqlClient;
namespace ConsoleApp2
{
class Program
{
private static void Main()
{
string conn = "Initial Catalog=world.sql;user=root;Server=127.0.0.1,3306";
MySqlConnection myConnection = new MySqlConnection(conn);
MySqlDataReader myReader = null;
string sql = "SELECT * FROM coutry";
MySqlCommand myCommand = new MySqlCommand(sql, myConnection);
myConnection.Open();
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
for (int i = 0; i < myReader.FieldCount; i )
{
Console.WriteLine(myReader[i].ToString());
}
}
myConnection.Close();
}
}
}
CodePudding user response:
Use a connection string format like this: Server=localhost;User=user_name;Database=db_name;Port=3306;Password=password;SSL Mode=None
and apart from that, never use the root account. Just create an account that has a password.
If you apply these things to your code, the error should disappear.
CodePudding user response:
use This connection in C#
Data Source=yourIpAddress,yourPort;Initial Catalog=YourdatabaseName;User ID=sqlserverUsername;Password=sqlserverpassword;MultipleActiveResultSets=True;" providerName="System.Data.EntityClient";