解析导致错误的查询 [英] Parsing a query that result in errors

查看:58
本文介绍了解析导致错误的查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个程序来扫描文件夹中的视频文件,然后通过数据库进行解析,然后将其添加到数据库(如果不存在).以下是执行检查的代码.

I''m writing a program to scan a folder for video files, parse it through the database, and then add it to the database if it dosn''t exist. The following is the code to do the check.

foreach (string filename in openFileDialog.FileNames)
{
  if (dlg.FileName != "")
  {
    string FilePattern = "SELECT * FROM Table WHERE Path = \"" + filename + "\"";
    string FileExist = "NO";
    SqlCeConnection con;
    try
    {
      con = new SqlCeConnection();
      con.ConnectionString = "Data Source=" + DataDirectory + "\\FilePath.sdf";
      {
        con.Open();
        using (SqlCeCommand cmd = new SqlCeCommand(FilePattern, con))
        {
          using (SqlCeDataReader reader = cmd.ExecuteReader())
          {
            while (reader.Read())
            {
              FileExist = "YES";
              MessageBox.Show("Already exist");
            }
          }
        }
      }
    }
    catch (SqlException ex)
    {
      Console.Write(ex);
    }
    if (FileExist == "NO")
      Save(filename);
  }
}



现在,当文件名中包含单引号时,问题就开始了.因为单引号启用了SqlException,所以它根本不会保存文件.有没有一种方法可以更改文件名,以允许其中带有('')的文件名继续运行.



Now the problem started when the filename had a single quote in it. It would simply not save the file because the single quote enables the SqlException. Is there a way to change the filename to allow filenames with ('') in them to still run.

推荐答案

您需要对''使用转义字符字符-类似于''.
You need to use the escape character for the '' character - something like ''''.


Google for"parameterized sql .net",您将找到大量示例,向您展示如何正确执行此操作,而不使用字符串连接就像您在代码段中所做的一样.
Google for "parameterized sql .net" and you''ll find tons of examples that show you how to do this properly and NOT use string concatentation like you''ve done in your snippet.


这篇关于解析导致错误的查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆