I am trying to get this code to pull from a sequel pro database using c# and MAMP and I keep getting the following error after I enter the city name that is for sure in the database. I don't understand why it's saying that the connection needs to be valid and open as I have an open script in the code.
Input City Orlando
Unhandled Exception: System.InvalidOperationException: Connection must
be valid and open.
at MySql.Data.MySqlClient.MySqlConnection.Throw(Exception ex)
at MySql.Data.MySqlClient.MySqlCommand.Throw(Exception ex)
at MySql.Data.MySqlClient.MySqlCommand.CheckState()
at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior
behavior)
at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader()
at ConsoleApp1.SQLWorker.GetData(String city) in
C:\Users\Colton10\Documents\Visual Studio 2017\Projects\SampleAPIData
2\project\Program.cs:line 35
at ConsoleApp1.Program.Main(String[] args) in
C:\Users\Colton10\Documents\Visual Studio 2017\Projects\SampleAPIData
2\project\Program.cs:line 61
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
namespace ConsoleApp1
{
class Data
{
public readonly decimal temp;
public readonly decimal pressure;
public readonly int humidity;
public readonly bool IsValid;
public Data(decimal t, decimal p, int h, bool v)
{
temp = t;
pressure = p;
humidity = h;
IsValid = v;
}
}
class SQLWorker
{
public static Data GetData(string city)
{
MySqlConnection connstring = new MySqlConnection("Server=
localhost; port = 8889; user = root; password = root; database =
sampleAPIData; SslMode = none ");
MySqlCommand command = connstring.CreateCommand();
var query = connstring.CreateCommand();
command.CommandText = string.Format("SELECT temp, pressure,
humidity FROM weather WHERE city='{0}' ORDER BY createdDate desc limit
1",
city);
MySqlDataReader reader = command.ExecuteReader();
connstring.Open();
try
{
reader.Read();
return new Data(reader.GetDecimal(0),
reader.GetDecimal(1),
reader.GetInt32(2), true);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
while(reader.Read());
return new Data(reader.GetDecimal(0), reader.GetDecimal(1),
reader.GetInt16(2), true);
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Input City");
string city = Console.ReadLine();
Data data = SQLWorker.GetData(city);
if (data.IsValid)
{
Console.WriteLine("{0}\n Temperature:{1} Pressure:{2}
Humidity:{3}\n", city, data.temp, data.pressure, data.humidity);
}
else
{
Console.WriteLine("No Data Available for the selected
city\n");
}
Console.ReadKey();
}
private static Data GetData(string city)
{
return SQLWorker.GetData(city);
}
}
}