c# - 系统.Data.SqlClient.SqlException : Incorrect syntax near the keyword 'file'

标签 c# asp.net

我是 AsP.net 的新手,当我尝试用我常用的代码连接到数据库时,一直显示异常,我不知道出了什么问题
异常(exception)是:

" System.Data.SqlClient.SqlException: Incorrect syntax near the keyword 'file'."

这是我的代码:

string ID = Request.QueryString["id"];

SqlCommand cmd = new SqlCommand("select title,file path,Upload Date from [Media] where ID=@id", conn);
cmd.CommandType = CommandType.Text;
SqlDataReader rdr=null;

try
{
    conn.Open();
    rdr = cmd.ExecuteReader();
    try
    {
        conn.Open();
        rdr = cmd.ExecuteReader();

        // print the CustomerID of each record
        while (rdr.Read())
        {
            pathTextBox.Text = rdr["file Path"].ToString();
            DateTextBox.Text = rdr["Upload Date"].ToString();
            titleTextBox.Text = rdr["title"].ToString();
        }

        Image1.ImageUrl = pathTextBox.Text;
    }

最佳答案

如果列名中有空格,则需要使用括号,如下所示

从 ID=@id 的 [Media] 中选择标题、[文件路径]、[上传日期]

using (var conn = new SqlConnection(SomeConnectionString))
using (var cmd = conn.CreateCommand())
{
    conn.Open();
    cmd.CommandText = "select title,[file path],[Upload Date] from [Media] where ID=@id";
    cmd.Parameters.AddWithValue("@id", idval); // set the id parameter
    using (var reader = cmd.ExecuteReader())
    {
        if (reader.Read()) // you don't need while loop
        {
            pathTextBox.Text = reader.GetString(reader.GetOrdinal("[file path]"))
        }
    }
}

关于c# - 系统.Data.SqlClient.SqlException : Incorrect syntax near the keyword 'file' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21580888/

相关文章:

c# - 快速从网页抓取图像

c# - EF Code-First 中查找表的最佳实践

c# - PayPal 支付标准从移动设备返回 GET 而不是 POST,因此无法验证记录支付

c# - Parse.com CurrentUser 始终为 null

c# - 加密和解密密码

asp.net - 如何在 Windows Server 2008 R2 上安装 PayPal API 证书

c# - 在新线程中启动表单并在它们之间引发事件

c# - 我需要将 2 列的数据合并到另一列。然后将该添加列的所有行合并到另一个表中的一个单元格中

c# - 从查询字符串中提取中文文本

asp.net - 如何以编程方式更改 div 的样式