Click here to Skip to main content
15,887,875 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am having a problem in retirieving the last value in a column in mysql db.
I am getting connection must be valid and open error.
Can someone please help?
Thanks

What I have tried:

String connString = System.Configuration.ConfigurationManager.ConnectionStrings["web"].ToString();
        using (MySqlConnection con = new MySqlConnection(connString))
        {
            using (MySqlCommand cmd = new MySqlCommand("SELECT TOP 1 idProyecto FROM proyectos order by idProyecto DESC LIMIT 1"))
            {
                cmd.CommandType = CommandType.Text;
                cmd.Connection = conn;
                con.Open();
                val1 = cmd.ExecuteScalar().ToString();
                con.Close();
                return val1;

            }
        }
Posted
Updated 25-Jan-18 7:56am
Comments
A_Griffin 25-Jan-18 13:52pm    
MySQL doesn't use the TOP function - remove that and just use the LIMIT 1 instead. However, from the error message I suspect that your connection string is invalid.

1 solution

Quote:
cmd.Connection = conn;

You've declared your connection object as "con" and then told your command object to use a connection object called "conn".

Since this actually compiled, it appears you've got another connection object called "conn" somewhere above this in the same scope or in a higher level scope. That would be bad practice to have that.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900