Leon
Leon

Reputation: 581

How to query from a database in ASP.NET?

I'm still somewhat new to ASP.NET and VB, and I found out that it's vastly different from the ASP I learned where I used Recordset to extract data from the database. Can someone give me some pointers on how to extract data from a database? Here is what I used to at least connect:

Dim conn As OdbcConnection
conn = New OdbcConnection("DSN=southwind")
Dim mystring as String = "SELECT GroupName FROM Group"
Dim cmd As OdbcCommand = New OdbcCommand(mystring, conn)

conn.Open()
Dim reader As OdbcDataReader = cmd.ExecuteReader()

The last line gives me an error saying:

Exception Details: System.Data.Odbc.OdbcException: ERROR [42000] [Microsoft][SQL Server Native Client 11.0][SQL Server]Incorrect syntax near the keyword 'Group'.

But since I don't quite understand ASP.NET completely, not too sure what it means even though the syntax looks fine. Removing that line runs the code just fine. How would I display all the contents from the GroupName column in table Group?

EDIT: Thanks everyone, I completely forgot that Group was reserved in SQL.

Upvotes: 0

Views: 235

Answers (2)

David Thompson
David Thompson

Reputation: 11

Group is a keyword in SQL. If your table name or column names referenced in your query are keywords, you can enclose them in brackets.

Dim mystring as String = "SELECT GroupName FROM [Group]"

Upvotes: 1

Afzaal Ahmad Zeeshan
Afzaal Ahmad Zeeshan

Reputation: 15860

Group is a keyword in SQL, you need to wrap it in square brackets like this,

SELECT GroupName FROM [Group]

This would assume the Group to be a name of the table, instead of a key word; of GROUP BY clause.

Upvotes: 3

Related Questions