【问题标题】:Sql parameter are not getting replacedSql 参数没有被替换
【发布时间】:2013-05-21 21:30:36
【问题描述】:

我正在尝试在基于 csv 文件的数据库中创建一个新表。因为我不知道 csv 文件中有哪些列,所以我在运行时创建了一个 SqlCommand 。这是我目前所拥有的。

public static void AddTableFromFile(string file)
{
    DefaultContext dbContext = DefaultContext.GetInstance();
    DbProviderFactory dbFactory = DbProviderFactories.GetFactory(dbContext.Database.Connection);

    SqlCommand createTable = new SqlCommand();
    createTable.Connection = (SqlConnection)dbContext.Database.Connection;

    //Get all the fields from the file.
    TextReader reader = File.OpenText(file);
    string head = reader.ReadLine();
    reader.Close();
    head = head.Replace('\"', ' ');

    //Build the column paramaters for the Sql query.
    string[] fields = head.Split(',');
    if (fields.Length == 0)
        throw new Exception("No data to process; " + file);
    StringBuilder columnsBuilder = new StringBuilder();
    for (int i = 0; i < fields.Count(); i++)
    {
         columnsBuilder.Append("@column" + i + " char(25), ");
         createTable.Parameters.AddWithValue("@column" + i, fields[i]);
    }
    //Make the first field the primary key.
    columnsBuilder.Append("PRIMARY KEY(@column0)");

    createTable.Parameters.AddWithValue("@tableName", Path.GetFileNameWithoutExtension(file));

    createTable.CommandText = "CREATE TABLE @tableName (" + columnsBuilder.ToString() + ")";

    dbContext.Database.Connection.Open();
    createTable.ExecuteNonQuery();
    dbContext.Database.Connection.Close();

    DefaultContext.Release();
    Logger.Log("Table " + Path.GetFileNameWithoutExtension(file) + " added to the database.");
}

但是,每次运行时,我都会收到一个 SqlException,告诉我 @tableName 周围存在语法错误。我通过将原始值放入字符串中尝试了相同的命令,所以我知道它有效。我在这里遗漏了什么明显的东西吗?

以防万一,我正在使用 MVC 4,我相信数据库是 Sql Server Express 或与 Visual Studio 2012 捆绑的任何一个。

【问题讨论】:

    标签: c# sql asp.net-mvc-4


    【解决方案1】:

    我在这里遗漏了什么明显的东西吗?

    很遗憾,我认为您遗漏了一些不受支持的内容。虽然 values 可以参数化,但据我所知,大多数数据库(包括 SQL 服务器)不允许对表名甚至字段名进行参数化。

    所以基本上,如果你真的需要能够接受字段等作为用户输入,你需要完成所有的工作 super - 注意接受的字符,转义值等等 - 然后直接放入 SQL 中。

    【讨论】:

      【解决方案2】:

      您不能使用参数作为表名。您可以使用它来比较值,例如

      WHERE UserName = @UserName
      

      如果您害怕 SQL 注入,请使用经典的.Replace("'","''")

      【讨论】:

      猜你喜欢
      • 2017-11-14
      • 2014-08-15
      • 2013-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-20
      • 2017-10-24
      • 1970-01-01
      相关资源
      最近更新 更多