I try to connect to a database using MySql.Data but it doesn’t work. What did i do wrong?
private List<Car> cars;
private MySqlConnection conn;
private static uint DB_PORT = 3306;
private static string DB_HOST="localhost";
private static string DB_USER = "root";
private static string DB_PASSWORD = "";
private static string DB_DATABASE = "database";
public ...()
{
cars = GetCars();
}
public List<Car> GetCars()
{
List<Car> cars = new List<Car>();
MySqlConnectionStringBuilder builder = new MySqlConnectionStringBuilder();
builder.Password = DB_PASSWORD;
builder.Port = DB_PORT;
builder.Database = DB_DATABASE;
builder.UserID = DB_USER;
builder.Server= DB_HOST;
conn = new MySqlConnection(builder.ConnectionString);
conn.Open();
string sql = "SELECT * FROM cars";
MySqlCommand cmd=new MySqlCommand(sql, conn);
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
int id = reader.GetInt32("id");
string license_plate_number = reader.GetString("license_plate_number");
string brand = reader.GetString("brand");
string model=reader.GetString("model");
int daily_cost = reader.GetInt32("daily_cost");
Car car=new Car(id, license_plate_number, brand, model,daily_cost);
cars.Add(car);
}
return cars;
}
It doesn’t send any error codes, but it doesn’t connect to the database succesfully because the list has no elements.
New contributor
Winetou001 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.