ASP.NET CSHTML - “关键字'user'附近的语法不正确。”

时间:2012-12-03 00:12:10

标签: asp.net .net sql razor webmatrix

我正在尝试学习如何使用CSHTML和.NET来做一个简单的数据库连接和查询输出到网站,但我有几个小时的问题,从我的连接字符串到实际查询我遇到了麻烦。请帮助我找到问题并使这个基本查询正常工作。

数据库= Microsft SQL Express
schema = id(int),user(nchar(10)),password(char(32))。

Web.Config的内容

<?xml version="1.0" encoding="utf-8"?>

<configuration>
   <connectionStrings>
   <add name="MyConnectionString"
     connectionString="Data Source=LAPTOP\SQLEXPRESS;Initial Catalog=databasename;Integrated Security=False;User ID=sa;Password=password" />        
</connectionStrings>
<system.web>
   <compilation debug="true" targetFramework="4.0" />
</system.web>
</configuration>

以下是我在查询中失败的尝试。我试图使用w3学校http://www.w3schools.com/aspnet/webpages_database.asp中的例子无济于事。

ListProducts.cshtml的内容

@{
var connectionString = "Data Source=LAPTOP\\SQLEXPRESS;Initial Catalog=databasename;    Integrated Security=True";
var providerName = "System.Data.SqlClient";
var db = Database.OpenConnectionString(connectionString, providerName);
var selectQueryString = "SELECT * from user";
}
<html> 
<body> 
<h1>Test</h1> 
<table> 
<tr>
<th>id</th> 
<th>username</th> 
<th>password</th> 
</tr>
@foreach(var row in db.Query(selectQueryString))
{
<tr> 
<td>@row.id</td> 
<td>@row.user</td> 
<td>@row.password</td> 
</tr> 
}
</table> 
</body> 
</html>

每次我跑步时都会收到此错误

Server Error in '/' Application.
Incorrect syntax near the keyword 'user'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Data.SqlClient.SqlException: Incorrect syntax near the keyword 'user'.

Source Error:


Line 14: <th>password</th> 
Line 15: </tr>
Line 16: @foreach(var row in db.Query(selectQueryString))
Line 17: {
Line 18: <tr> 

3 个答案:

答案 0 :(得分:3)

尝试将user括在方括号中:

var selectQueryString = "SELECT * from [user]";
SQL中的

usera reserved word

答案 1 :(得分:0)

猜测问题与数据库(初始目录)有关。

Data Source=LAPTOP\\SQLEXPRESS;Initial Catalog=databasename

您的数据库是否真的命名为“databasename”?

答案 2 :(得分:0)

原来它一定与我的数据库有关。我有一个名为user的表,其中一列也称为user。我将表用户重命名为用户,更新了代码,现在一切正常!