目前正在研究音乐猜想程序。我有用户输入的歌词,程序将尝试查找匹配项。如果程序找到一个,它将显示歌手姓名。目前,我正在尝试运行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();
}
}
}
}
答案 0 :(得分:2)
改为执行此操作
string uI = "%" + Console.ReadLine() + "%";
您还可以进行字符串插值
string uI = $"%{Console.ReadLine()}%";
还有您的SQL语句
String cmdText = "SELECT Artist FROM Songs WHERE Lyrics LIKE @uI";
答案 1 :(得分:1)
您可以在命名参数上使用字符串连接。在 MySql 中,您可以尝试使用concat运算符 || (取决于版本,config)或 concat 函数
... LIKE ('%@ uI%')的意思... LIKE concat('%',@ uI,'%')
SELECT Artist FROM Songs WHERE Lyrics LIKE concat('%',@uI,'%')