2013-05-21 29 views
3

我想在我的数据库中基于csv文件创建一个新表。由于我不知道csv文件中有哪些列,我在运行时创建了一个SqlCommand。这是我到目前为止。Sql参数没有被替换

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

回答

6

我在这里错过了一些明显的东西吗?

不幸的是,我想你错过了一些不受支持的东西。尽管可以参数化,但据我所知,大多数数据库(包括SQL服务器)不允许参数化表名或字段名。

因此,基本上,如果你真的需要能够接受字段等作为用户输入,你需要经历的所有工作 - 对所接受的字符,转义值等的重视 - 然后直接将其放入SQL中。

2

你不能使用表名参数捆绑在一起。您可以使用它来比较数值,例如

WHERE UserName = @UserName 

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

+1

.Replace(“'”,“''”)如何防止SQL注入? – dkellycollins

+0

那么,AFAIK它不是100%安全的,但它会导致有人通过撇号时(这是人们通常在尝试注入代码时所做的)SQL查询无效。 – rocky

+0

参见例如http://stackoverflow.com/questions/8506574/sql-injection-isnt-replace-good-enough了解更多信息... – rocky