简体   繁体   English

Visual Studio中的SQL Like查询

[英]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 我可以使其他查询正常工作,但无法在Visual Studio中使此查询正常工作假定在此函数之外声明了ConnectionString

public DataTable GetDtSearch(string searchname) { 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. PPS另外,由于不建议使用Add(string,object)签名,因此请使用AddWithValue方法。

Put quotes around the search param. 在搜索参数周围加上引号。 - --
SELECT * FROM table WHERE (file_name LIKE '@searchname')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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