rfa
rfa

Reputation: 53

mysql command executescalar returns null in C#

Let's say I have a query result that looks as follows:

ID    NAME    Phone
----  ----    -----
1     John    123456
2     John    125678
3     John    345678
4     Abby    456789
5     Abby    567890

I want to return just a single row instance of name: John, where the phone number like '12%'.

In c#, I wrote this syntax to get the PersonName variable as the result of the query.

MySqlConnection connection = new MySqlConnection("SERVER=" + "localhost" + ";" + "DATABASE=" + "testdb" + ";" + "UID=" + "root" + ";" + "PASSWORD=" + "" + ";");
MySqlCommand command = new MySqlCommand();    

    connection.Open();
    string selectQuery = "SELECT NAME FROM testtable WHERE Phone LIKE '12%' ORDER BY ID LIMIT 1";
    command.Connection = connection;
    command.CommandText = selectQuery;
    string PersonName = (string)command.ExecuteScalar();
    connection.Close();

I don't know whats wrong with my code but the PersonName returns null. What did I do wrong?

Upvotes: 0

Views: 2439

Answers (2)

bigtheo
bigtheo

Reputation: 660

do this : change this (string)command.ExecuteScalar(); by Convert.ToString(command.ExecuteScalar());

MySqlConnection connection = new MySqlConnection("SERVER=" + "localhost" + ";" + "DATABASE=" + "testdb" + ";" + "UID=" + "root" + ";" + "PASSWORD=" + "" + ";");

MySqlCommand command = new MySqlCommand();

connection.Open();
string selectQuery = "SELECT NAME FROM testtable WHERE Phone LIKE '12%' ORDER BY ID LIMIT 1";
command.Connection = connection;
command.CommandText = selectQuery;
string PersonName = Convert.ToString(command.ExecuteScalar());
connection.Close();

Upvotes: 0

Eric Walker
Eric Walker

Reputation: 1052

We have to be missing something else here. Try the following code sample based on what you provided:

try {
MySqlConnection connection = new MySqlConnection("SERVER=localhost;DATABASE=testdb;UID=root;PASSWORD=;");
MySqlCommand command = new MySqlCommand();    

connection.Open();
string selectQuery = "SELECT NAME FROM testtable WHERE Phone LIKE '12%' ORDER BY ID LIMIT 1";
command.Connection = connection;
command.CommandText = selectQuery;
string PersonName = (string)command.ExecuteScalar();
}
catch (Exception ex) {
MessageBox.Show(ex.Message);
}
finally {
    connection.Close();
}

I have a feeling that for some reason the call to .Open() is failing and the error is being swallowed elsewhere. Try the above and let me know what you find out.

Upvotes: 1

Related Questions