How to query from a database in ASP.NET? - 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.

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.

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]"

Related

ASP.net commands to SQL dbo

I've very new to ASP.net. However, I am currently working on a project and I am trying to change the table that this ASP.net application is pointing to.
I know that the key to doing this lies in figuring out how the following is set in my Default.aspx.vb file:
Dim cmdText as String = "[up_getPrevention]"
Using command As SqlCommand = New SqlCommand(cmdText, conn)
command.CommandType = CommandType.StoredProcedure
command.Parameters.AddWithValue("#userid", usr)
Does anyone know what the [] means in the statement above? I know that typically the SQL statement (ie. SELECT) is within those double quotes...
Thanks for your help!
if the sp name we are writing is a keyword of SQL itself then we need to put [] at start and end of it...
Like 'Table'

why is oledb dataadapter not fetching any data from access database in vb.net?

I am stuck with a very peculiar problem. I am working in asp .net vb with ms access 2007
Inorder to fetch data I am using the following code snippet
connection = utility.GetConnection()
Dim command As New OleDbCommand(sQuery, connection)
Dim adapter As New OleDbDataAdapter(sQuery, connection)
Dim dt As New DataTable()
adapter.SelectCommand = command
adapter.Fill(dt)
When I use the query without the where clause it works. i.e. IT fetches all the rows and fills the data table. But when the sQuery has the where clause with it dt.Rows.Count always gives 0. i.e. no data is fetched from database. I saying this is a peculier problem because while debigging I copied the sQuery with where clause and ran in the ms access and there it is returning the data. I don understand what am I missing.
I am showing the queires that is generated for sQuery
SELECT * FROM ORDER_VIEW WHERE 1 = 1 (I don have any problem with that)
But when sQuery has
SELECT * FROM ORDER_VIEW WHERE 1 = 1 AND ITEM_ID_NO LIKE '011*'
It fetches rows in the ms access but, adapter.Fill(dt) line does not fill datatable with any row
I am stuck with this problem, for any suggesion and solution thanks in advance.
When using the OleDB provider, try using '011%' instead of '011*'.
I believe the OleDB engine uses the % for a wild card character where the Access engine uses the * character. It comes down to the provider.

Parameterized Update Query for Sql server in ASP.net with VB

I am trying to write a paramaterized update query to insert values into an Sql Server Express Database. The query I have written is:
Dim cmd As New SqlCommand
cmd.Connection = conn
cmd.CommandText = "update tblposts set title=#ptitle, pdate=#pd,
content=#pcontent where pid=#p"
cmd.Parameters.AddWithValue("ptitle", txtTitle.Text)
cmd.Parameters.AddWithValue("pcontent", txtcontent.InnerText)
cmd.Parameters.AddWithValue("pd", DateTime.Now.ToString)
cmd.Parameters.AddWithValue("p", postid)
On running cmd.ExecuteNonQuery, I get number of rows affected as 1, but the change is not reflected in the database.
On printing the query using Debug.Write, I get the query not with the parameter values, but the names of the parameters itself (ie. #pcontent, #title etc)
What can be the mistake here?
In you're AddWithValue you need to include the # symbol on the front of the parameter, so:
cmd.Parameters.AddWithValue("#ptitle", txtTitle.Text)
cmd.Parameters.AddWithValue("#pcontent", txtcontent.InnerText)
cmd.Parameters.AddWithValue("#pd", DateTime.Now.ToString)
cmd.Parameters.AddWithValue("#p", postid)
I'm guessing that it's executing correctly but there where clause is blank, so perhaps updating a blank row.
Anyway, try the above and it should update as expected.
Edit to Add
The CommandText will always only have the #value in there, it will not substitue the parameter values into the string.
You would need to loop through the cmd.Parameters collection to write out the values.

asp.net sqlcommand not doing as it should - debugging help req

This is a really odd situation that I can't seem to work out where the problem lies.
I have a simple ASP textbox and button, on clicking the button I have a simple sqlconnection/command routine perform a simple update to a database based on the text value of the textbox.
Code:
Using myConnection As SqlConnection = New sqlConnection(ConfigurationManager.ConnectionStrings("sqldbconn").ConnectionString)
myConnection.Open()
Dim strSQL As String = "insert into users(name) select #name"
Dim myCommand As New Data.SqlClient.SqlCommand(strSQL, myConnection)
myCommand.CommandType = Data.CommandType.Text
myCommand.Parameters.Add(create_Parameter("#name", Data.SqlDbType.VarChar, 50, Data.ParameterDirection.Input, txName.Text))
myCommand.ExecuteNonQuery()
myConnection.Close()
End Using
create_Parameter is just a simple tested function which performs the 2-3 lines it normally takes to create a parameter object.
The problem I have, is that the value added to the database is always a comma, followed by the text given in the textbox.
I have performed response.write's prior to the ExecuteNonQuery call to check both the Parameter value and the CommandText, which are fine and as expected. If I copy what's expected into a management studio query window, it works fine.. users is a simple table with varchar column, no triggers or constraints etc. There are no other sub's in the ASP code other than what I've shown.
So now I'm stuck, what else can I do to work out where/why this comma is being added to my insert statement???
Cheers!
Probably nothing to do with your issue, but I wold normally write an insert like this:
INSERT INTO users (name)
VALUES #name

Integer variable is acquiring a string value of "ad" somewhere along the line, can anyone see where?

Here is my code:
I should get output of the department id (did) as an integer and the templatefilename (result) that is required.
The errors I get are: Conversion from string "ad" to type 'Integer' is not valid. I'm fairly new to asp.net and cannot see where the did variable picks up the "ad" string.
Any help would be greatly appreciated.
Thanks
When you construct the query to the table departmentsgroupings, you're changing the value of sql, but you aren't creating a new SqlCommand. This means that cmd still contains the old SQL statement (the query to the Modules table) which, when executed, returns "ad".
To fix this, change your code as follows:
sql = ("select departmentsid from departmentsgroupings where groupingid =" & pageid & "")
Set cmd = New SqlCommand(sql, conn)
did = (cmd.ExecuteScalar)
You may have expected the change you made to sql to get passed on automatically to the SqlCommand -- but it doesn't work that way.
Edit: Your code, as written, is vulnerable to SQL injection attacks. If you don't know what these are, you need to read the first answer to this:
How does the SQL injection from the "Bobby Tables" XKCD comic work?
To protect yourself against these kinds of attacks, use parameterized queries.
The mistake is in these lines:
sql = ("select departmentsid from departmentsgroupings where groupingid =" & pageid & "")
did = (cmd.ExecuteScalar) <---- Wrong command executed here.
You presumably meant to execute the code in sql, not cmd again.

Resources