【问题标题】:Why do I receive a incorrect syntax error while creating a table in C#为什么在 C# 中创建表时收到不正确的语法错误
【发布时间】:2014-07-31 13:06:06
【问题描述】:

我正在尝试使用从 CSV 文件中读取的标题创建一个表:

myConnection = new SqlConnection(cString);
myConnection.Open();

var lines = File.ReadLines(textBox1.Text);
List<string> readHeader = lines.ElementAt(0).Split(',').ToList();
string tab = "a123CSV";
readHeader.ToArray();
string exists = null;
try
{
   SqlCommand cmd = new SqlCommand("SELECT * FROM sysobjects where name = '" + tab + "'", myConnection);
   exists = cmd.ExecuteScalar().ToString();
}
catch (Exception ce)
{
   exists = null;
}

if (exists == null)
{
   int p;
   for (p = 0; p <= readHeader.Count; p++)
   {
      if (exists == null)
      {
         SqlCommand createTable = new SqlCommand("CREATE TABLE '" + tab + "' ([" + readHeader[p] + "] varchar(MAX))", myConnection);
         createTable.ExecuteNonQuery();
         exists = tab;
      }
      else
      {
         SqlCommand addcolumn = new SqlCommand("ALTER TABLE '" + tab + "' ADD [" + readHeader[p] + "] varchar(MAX)", myConnection);
         addcolumn.ExecuteNonQuery();
      }
   }
}

CSV 文件中的标题是这样的:

"NPI","实体类型代码","替换 NPI","雇主标识 编号 (EIN)","提供商组织名称(法律业务 Name)","Provider Last Name (Legal Name)","Provider First 名称","提供者中间名","提供者名称前缀文本"

每当我运行我的应用程序时,我都会在这一行收到此错误:

...
if (exists == null)
{
SqlCommand createTable = new SqlCommand("CREATE TABLE '" + tab + "' ([" + readHeader[p].Replace("\"", "") + "] varchar(MAX))", myConnection);
createTable.ExecuteNonQuery();
...

错误:

Incorrect syntax near `a123CSV`

我该如何解决这个错误?

【问题讨论】:

  • 首先要解决的问题:停止将值直接嵌入到您的 SQL 中。使用参数化 SQL。这可能足以使 other 错误更加明显......同时还修复了 SQL 注入攻击漏洞。
  • 一旦查询正常,我将使用参数 :) 感谢您的反馈
  • @JonSkeet 参数化查询是否能够动态指定要创建的表的名称?我不认为这是他们可以执行的有效任务。
  • @Servy:不是那个位,不是 - 但除了表名之外,还有一些代码需要修复other
  • @SearchForKnowledge:您应该从一开始就养成使用参数化查询的习惯。这就像说“在我完成之前,我不会费心格式化我的代码或使用有意义的变量名。”

标签: c# sql csv


【解决方案1】:

那是因为您将 TABLE_NAME 括在单引号内。用这个,

SqlCommand createTable = new SqlCommand("CREATE TABLE " + tab + " ([" + readHeader[p].Replace("\"", "") + "] varchar(MAX))", myConnection);

【讨论】:

  • 我会将单引号替换为[],以防用户提供的表名有空格。
  • @SearchForKnowledge 直到用户输入表名]; drop table sysobjects; --
  • 我在文本框中使用过滤器来确保只允许字母和数字,并且只允许字母作为第一个字符。 :)
【解决方案2】:

您需要使用[] 而不是单引号来转义表名,即:

"CREATE TABLE [" + tab + "] ([" + readHeader[p].Replace("\"", "") + "] varchar(MAX))"

【讨论】:

  • 我的错,我不是这么看的。谢谢你:)
  • @SearchForKnowledge:没问题,很乐意提供帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-12-13
  • 2020-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-11
  • 1970-01-01
相关资源
最近更新 更多