简体   繁体   中英

SQL Like Query in visual studio

I can get other queries to work but I can't get this query to work in Visual Studio Assuming ConnectionString is declared outside this function

public DataTable GetDtSearch(string searchname) {

        string sql = "SELECT * FROM table WHERE (file_name LIKE @searchname)";


        DataTable dt = new DataTable();

        using (MySqlConnection con = new MySqlConnection(ConnectionString))
        {

            try
            {
                con.Open();
            }
            catch { return dt; }

            using (MySqlCommand cmd = new MySqlCommand(sql, con))
            {
                cmd.Parameters.Add(@searchname,"%"+ searchname+"%");
                using (MySqlDataAdapter adp = new MySqlDataAdapter(cmd))
                {
                    try
                    {
                        adp.Fill(dt);
                    }
                    catch
                    {

                    }

                }

            }
            con.Close();
        }




        return dt;
    }
       cmd.Parameters.Add("@searchname","%"+ searchname+"%");

Enclose the parameter name (first argument) in quotation marks.

PS I've upvoted your downvoted question, but the downvoter was right to do so -- you need to say what's happening -- an error message, or "no results are returned" or something more precise than "can't get this query to work".

PPS Also, use the AddWithValue method, since Add(string, object) signature has been deprecated.

Put quotes around the search param. -
SELECT * FROM table WHERE (file_name LIKE '@searchname')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM