Neo Essence
Neo Essence

Reputation: 17

Getting a String from a value in Mysql in C#

i have the following table in MySql :

ID          Name

1           Google
2           Yahoo
3           Facebook
4           Whatever

I have a textfield that when someone writes something and presses a button it stores this value in a string. This string is the Name of the above table. Then i have my code about selecting the id referred to that name. Ex, if the user enters Facebook i will find that the ID = 3. this is the code :

    public bool FindCompanyID(string companyName)
{
    return ExecQuery("select id from companies where name=@name",
        cmd =>
        {
            cmd.CommandText = "SELECT id from companies WHERE name ='" + companyName + "'";
            return cmd;
        });
}

I want someone to show me a sample of code about the following : Saving to a string the " id " . if the ID in the database = 2 i want to make a

int Company_Number_ID

that i will use. How can i get the string to read the specified value from the database?

Upvotes: 0

Views: 569

Answers (1)

Magesh Kumaar
Magesh Kumaar

Reputation: 1467

I am guessing your return type is bool to check whether the DDL statements were executed successfully.

MySqlCommand cmd = dbConn.CreateCommand();
cmd.CommandText = "SELECT id from companies WHERE name ='" + companyName + "'";

try
{
    dbConn.Open();                
    Company_Number_ID = (Int32)cmd.ExecuteScalar();
} catch (Exception e) {
    //Exception occured. Handle it here
}

Note: cmd.Parameters.AddWithValue("@companyName",companyName). this is more secure

Edit: As pointed out in the comment by user3185569 , ExecuteScalar is better if you are sure it'll return only one row. But since no such information was provided. I did not consider that.

You can use ExecuteScalar directly like this.

Company_Number_ID = (Int32)cmd.ExecuteScalar();

Upvotes: 2

Related Questions