I’m trying to learn how to use CSHTML and .NET to do a simple db connection and query output to a website but I’m having hours of problems, from my connection string to the actual query I’ve had trouble. Please help me locate the problem and get this basic query to work.
Database=Microsft SQL Express
schema= id (int), user ( nchar(10) ), password (char(32) ).
Contents of 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>
And below is my failed attempt at a query. I tried to use the examples from w3 schools http://www.w3schools.com/aspnet/webpages_database.asp to no avail.
Contents of 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>
And every time I run I get this error
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>
Try enclosing
userin square brackets:useris a reserved word in SQL.