我是 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/