我正在尝试学习如何使用 CSHTML 和 .NET 进行简单的数据库连接和查询输出到网站,但我遇到了数小时的问题,从我的连接字符串到我遇到的实际查询都有问题。请帮助我找到问题并让这个基本查询正常工作。
数据库=Microsft SQL Express
架构= id (int)、用户 (nchar(10))、密码 (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>