如何在 C 中将路径作为参数传递给 MySQL 查询#

How do you pass a path as a parameter to a MySQL query in C#

提问人:SoloWharf 提问时间:11/4/2023 更新时间:11/5/2023 访问量:54

问:

我正在尝试将图像的路径和文件名保存到表格中,但它不起作用。AddParameterWithValue 成员似乎将我传递的字符串中的所有斜杠加倍,然后 ExecuteNonQuery 引发错误。我到处找,找不到解决方案。

该表称为“images”,有三列:id(自动递增的 int)、path(字符串)、filename(字符串)。

这是我的代码:

using (MySql.Data.MySqlClient.MySqlConnection mySqlConnection = new MySql.Data.MySqlClient.MySqlConnection(Settings.Default.tlConnectionString))
            {
                try
                {
                    mySqlConnection.Open();
                    string cmdText = "INSERT INTO images ('path', 'filename') VALUES (@path, @filename);";
                    MySqlCommand cmd = new MySqlCommand(cmdText, mySqlConnection);
                    cmd.Parameters.AddWithValue("@path", @Path.GetDirectoryName(itemFilePath));
                    cmd.Parameters.AddWithValue("@filename", Path.GetFileName(itemFilePath));
                    cmd.ExecuteNonQuery();
                    long imageId = cmd.LastInsertedId;

                    // more code here ...
                }
                catch (Exception e)
                {
                    return false;
                }
            }
            return true;

我收到的错误消息是这样的:

{“你的 SQL 语法有错误;查看与您的MySQL服务器版本相对应的手册,了解在''path', 'filename') VALUES ('\\\\\1215608140\\

您会注意到,它使所有反斜杠加倍。

正确的语句应该是

插入 。(, )值 ('\\\\srvdata\\images\\products', '8418-(1215608140).jpg');myschemaimagespathfilename

C# MySQL

评论

0赞 gunr2171 11/4/2023
您如何检查结果?如果在执行期间使用调试器检查它,它可能会显示双倍的斜杠,而这实际上意味着转义的斜杠。Path.GetDirectoryName(itemFilePath)
2赞 gunr2171 11/4/2023
为什么要引用要插入的列名?
0赞 Ňɏssa Pøngjǣrdenlarp 11/4/2023
为什么要从文件名中拆分路径?没有另一个,任何一个都没有任何用处
2赞 Bill Karwin 11/4/2023
错误在于在列名两边使用单引号,例如 .在 SQL 中,单引号用于字符串文字。MySQL使用反引号来分隔列名等标识符。请参阅 stackoverflow.com/questions/11321491/...'path', 'filename'
0赞 Luuk 11/5/2023
这回答了你的问题吗?何时在 MySQL 中使用单引号、双引号和反引号

答:

1赞 Revanth Shalon 11/4/2023 #1

我尝试了这段代码,它对我有用。你能再检查一次这是否有效吗?此处唯一的更改是将 CommandType 添加为 CommandType.Text 并从命令文本中删除引号

//Assuming this correct file path
string filePath = @"\\srvdata\images\products\8418-(1215608140).jpg";

using(var mySqlConnection = new MySQl.Data.MySQlClient.MySQlConnection(Settings.Default.tlConnectionString)
{
 try{
  mySqlConnection.Open();
  string commandText = "INSERT INTO images (path, filename) VALUES (@path, @filename);";
  var cmd = new MySqlCommand(commandText, mySqlConnection);
  cmd.CommandType = CommandType.Text;
  cmd.Parameters.AddWithValue("@path", Path.GetDirectoryName(filePath));
  cmd.Parameters.AddWithValue("@filename", Path.GetFileName(filePath));
  int result = cmd.ExecuteNonQuery();
  if(result!=-1)
  {
   Console.WriteLine("Success");
  }
  else
  {
   throw new Exception("Failure");
  }
 }
 catch(Exception ex)
 {
   Console.WriteLine(ex.Message);
 }
 finally
 {
  mySqlConnection.Close();
 }
}

评论

0赞 Bradley Grainger 11/5/2023
@gunr2171 正如您已经指出的,这是解决 OP 问题需要进行的唯一更改。(您可以考虑将其添加为答案;我会投赞成票。
0赞 SoloWharf 11/6/2023
谢谢 Revanth,也在这里工作。👌