为什么这种语法不正确?
描述:执行当前Web请求期间发生了未处理的异常。请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息。
异常详细信息:System.Data.SqlClient.SqlException:'('。
附近的语法不正确来源错误:
Line 43: "VALUES (@0, @1, @2, @3)";
Line 44:
Line 45: db.Execute(sql, title, content, 1, slug); <--------
Line 46: }
Line 47: }
这是我的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using WebMatrix.Data;
/// <summary>
/// Summary description for PostHandler
/// </summary>
public class PostHandler : IHttpHandler
{
public PostHandler()
{
//
// TODO: Add constructor logic here
//
}
public bool IsReusable
{
get { return false; }
}
public void ProcessRequest(HttpContext context)
{
var title = context.Request.Form["postTitle"];
var content = context.Request.Form["postContent"];
var slug = CreateSlug(title);
using (var db = Database.Open("DefaultConnection"))
{
var sql = "SELECT * FROM Posts WHERE Slug = @0";
var result = db.QuerySingle(sql, slug);
if (result != null)
{
throw new HttpException(409, "Slug is already in use.");
}
sql = "INSERT INTO Posts (Title, Content, AuthorId, Slug" +
"VALUES (@0, @1, @2, @3)";
db.Execute(sql, title, content, 1, slug);
}
}
private static string CreateSlug(string title)
{
title = title.ToLowerInvariant().Replace(" ", "-");
title = Regex.Replace(title, @"[^0-9a-z-]", string.Empty);
return title;
}
}
以下是我的数据库的样子,我使用的是Microsoft SQL Server Management Studio:
答案 0 :(得分:1)
sql = "INSERT INTO Posts (Title, Content, AuthorId, Slug) " +
"VALUES (@0, @1, @2, @3)";
你错过了一个正确的人。如果您阅读了错误消息,或者将插入命令逐字复制到外部工具(例如SQL Server Management Studio甚至记事本)中,这将是显而易见的。
使用任何语言的括号和花括号的好经验法则是你应该有一个相同的数字。