为什么我在INSERT INTO语句中出现语法错误?

时间:2014-09-29 09:47:57

标签: c# asp.net ms-access

protected void btnUpload_Click(object sender, EventArgs e)
{
    if (FileUpload1.PostedFile != null)
    {
        string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
        //Save files to disk
        FileUpload1.SaveAs(Server.MapPath("" + FileName));

        //Add Entry to DataBase
        String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["conString"].ConnectionString;

        OleDbConnection con = new OleDbConnection(strConnString);

        string strQuery = "INSERT INTO image([FileName],[FilePath],[AlbumName]) Values(@FN, @FP, @AN)";

        OleDbCommand cmd = new OleDbCommand(strQuery);

        cmd.Parameters.AddWithValue("@FN", FileName);
        cmd.Parameters.AddWithValue("@FP", "images/" + FileName);
        cmd.Parameters.AddWithValue("@AN", txtAlbumname.Text.ToString());

        cmd.CommandType = CommandType.Text;
        cmd.Connection = con;
        try
        {
            con.Open();
            cmd.ExecuteNonQuery();
        }

        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }

        finally
        {
            con.Close();
            con.Dispose();
        }
    }
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
    string var = DropDownList1.SelectedItem.ToString();
    txtAlbumname.Text = var.ToString();
}
}

我已经尝试了几乎所有的东西,但是这个错误还在继续。 我已添加括号以及保留字,但仍然显示此错误

2 个答案:

答案 0 :(得分:1)

OLE DB .NET设置为Text时,OleDbCommand Provider不支持将参数传递给SQL语句或CommandType调用的存储过程的命名参数。在这种情况下,必须使用question mark (?)占位符。例如:

SELECT * FROM Customers WHERE CustomerID = ?

因此,OleDbParameter对象添加到OleDbParameterCollection的顺序必须直接对应于命令文本中参数的问号占位符的位置。

例如

OleDbCommand command = new OleDbCommand(queryString, connection);
command.CommandText = 
    "SELECT CustomerID, CompanyName FROM Customers WHERE Country = ? AND City = ?";
command.Parameters.Add(parameters);

for (int j=0; j<parameters.Length; j++)
{
    command.Parameters.Add(parameters[j]) ;
}

供参考.. MSDN

答案 1 :(得分:0)

IMAGE是Access SQL中的reserved word,因此要将其用作表名,还必须将其括在方括号中:

string strQuery = "INSERT INTO [image] ([FileName], ...