【问题标题】:Trying to make a user input go through a LIKE SQL statement试图使用户输入通过 LIKE SQL 语句
【发布时间】:2019-03-18 02:24:19
【问题描述】:

目前正在开发音乐猜测程序。我让用户输入歌词,程序将尝试找到匹配项。如果程序找到了,它将显示艺术家姓名。目前我正在尝试运行 SELECT 语句来查找最相关的匹配项。当我对元素进行硬编码时,控制台会给我艺术家,但是当我尝试将其设置为用户输入时,它什么也不显示。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
using System.Data;


namespace Databasetesting
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Start\n");

            // MySQL Database Connection String
            string cs = @"server=192.168.0.5;userid=***;password=***;database= Music_Mixer;port=8889";

            // set up connection
            MySqlConnection con = null;

            // make a reader
            MySqlDataReader  reader = null;

            Console.WriteLine("Please enter song lyrics:");
            string uI = Console.ReadLine();

            // write a try catch statement   
            try
            {
                // cal in database
                con = new MySqlConnection(cs);

                // open connection
                con.Open();

                // Statement
                String cmdText = "SELECT Artist  FROM Songs WHERE Lyrics LIKE ('%@uI%')";

                // make a new command
                MySqlCommand cmd = new MySqlCommand(cmdText, con);

                // binding
                cmd.Parameters.AddWithValue("@uI", uI);

                // make reader = to new command
                reader = cmd.ExecuteReader();

                // run the reader and display to user
                while (reader.Read())
                {
                    string Artists = reader["Artist"].ToString();
                    Console.WriteLine(Artists);
                }
            }
            catch(MySqlException er)
            {
                Console.WriteLine(er);
            }
            finally
            {
                if(con != null)
                {
                    con.Close();
                }
                Console.ReadLine();
            }
        }
    }
}

【问题讨论】:

  • 如果UI 的值是mj%wills,你期望会发生什么?
  • 我一定会继续阅读使用。我这个月才开始使用 sequel pro 上课。我已经在 c# 中工作了一段时间了。

标签: c# sql database visual-studio


【解决方案1】:

改为这样做

string uI = "%" + Console.ReadLine() + "%";

你也可以做字符串插值

string uI = $"%{Console.ReadLine()}%";

还有你的 SQL 语句

String cmdText = "SELECT Artist  FROM Songs WHERE Lyrics LIKE @uI";

【讨论】:

    【解决方案2】:

    您可以在命名参数上使用字符串连接。在 MySql 中,您可以尝试 concat 运算符 || (取决于版本、配置)或 concat 函数

    isntead of ...LIKE ('%@uI%') 去... LIKE concat('%',@uI,'%')

    SELECT Artist  FROM Songs WHERE Lyrics LIKE concat('%',@uI,'%')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-11
      • 2021-10-03
      • 2020-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-03
      • 2011-10-08
      相关资源
      最近更新 更多