Tuesday, March 20, 2012

Question about getting a value

I have the following script (Trimmed down to show you)

1 Dim myConnection As OleDbConnection
2 Dim myCommand As OleDbCommand
3 Dim intUserCount As Integer
4 Dim LoggedInUserId As Integer
5 Dim strSQL As String
6
78strSQL = "SELECT intUserID FROM tblUsers " _
9& "WHERE txtUsername='" & Replace(txtUsername.Text, "'", "''") & "' " & "AND txtPassword='" & Replace(txtPassword.Text, "'", "''") & "';"
1011 myConnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; " _
12 & "Data Source=" & Server.MapPath("DB.mdb") & ";")
1314 myCommand = New OleDbCommand(strSQL, myConnection)
1516 myConnection.Open()
17LoggedInUserId = myCommand. <<<<
18 myConnection.Close()

I have bolded the line where I am stuck (17)... I need to return the the value of the selected row and append it to the variable shown... What command do I need to use?

since you would be returning only one value from your SELECT statement, ExecuteScalar would work the best.|||

Thanks ... I had actually put that and got it to work, but what if I need to return a specific row (For example say my select was grabbing 2 columns)?? What would I need to use then??

Thanks again in advance...

|||

Forgot to put as when I use ASP I can simply put something like


mycommand("intUserID")

?? Don't seem to be able to do anything like that with .NET ? Or can you??

|||You could use ExecuteReader.|||

Hey ndinakar ...

So how would I use that ..

ExecuteReader("intUserID") ... ?? Like that??

|||Please check out the documentation or even Google. I can point you in the right direction but I cannot write code for you.|||If you could point me towards a code sample using this method it would be appreciated... everything I find on Google doesn't show any examples?|||It took me 5 seconds to find this link on google:http://authors.aspalliance.com/aspxtreme/sys/data/sqlclient/SqlCommandClassExecuteReader.aspx|||

From link:

C#:void ExecuteReaderDemo ( string query, string connString ) { SqlConnection myConn = new SqlConnection ( connString ); SqlCommand myCommand = new SqlCommand ( query, myConn ); myCommand.Connection.Open ( ); SqlDataReader myReader = myCommand.ExecuteReader ( CommandBehavior.CloseConnection );while ( myReader.Read ( ) ) { Response.Write ( myReader.GetString ( 0 ) ); } myReader.Close ( ); myConn.Close ( );}VB:Public Sub ExecuteReaderDemo ( queryAs String, connStringAs String ) Dim myConnAs New SqlConnection ( connString ) Dim myCommandAs New SqlCommand ( query, myConn ) myCommand.Connection.Open ( ) Dim myReaderAs SqlDataReader = _ myCommand.ExecuteReader ( CommandBehavior.CloseConnection )While myReader.Read ( ) Response.Write ( myReader.GetString ( 0 ) )End While myReader.Close ( ) myConn.Close ( )End Sub
You can also reference the columns like (Instead of myReader.GetString(MyColumnNumber)):
C#: myReader["Mycolumn"]
VB: myReader("MyColumn")
|||Fantastic ... Thanks!!!

No comments:

Post a Comment