1

CSHTMLと.NETを使用して単純なdb接続を実行し、Webサイトへのクエリ出力を行う方法を学習しようとしていますが、接続文字列から実際のクエリまで、何時間も問題があります。問題を特定し、この基本的なクエリを機能させるのを手伝ってください。

Database = Microsft SQLExpress
スキーマ=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> 
4

3 に答える 3

3

user角かっこで囲んでみてください。

var selectQueryString = "SELECT * from [user]";

userSQLで予約語です。

于 2012-12-03T01:00:36.927 に答える
0

問題の推測はデータベース(初期カタログ)に関連しています。

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

あなたのデータベースは本当に「データベース名」という名前ですか?

于 2012-12-03T00:27:34.683 に答える
0

それは私のデータベースに関連したものだったに違いありません。userという列とuserという列を持つuserというテーブルがありました。テーブルuserの名前をusersに変更し、コードを更新しました。これですべて正常に機能します。

于 2012-12-03T00:57:34.477 に答える