Getting just one field value from database

Pnew

New member
Joined
Sep 18, 2006
Messages
1
Programming Experience
Beginner
I would like to be able to use just one field value from my database and set a variable to it. However, I am not sure I am going about getting it the right way.

What I have here is a database with a field called adminPW. I would like to retrieve the value in it and set a variable to it so I can use it in my code. This should be such a simple task. Any help here?

VB.NET:
[SIZE=2]conn = [/SIZE][SIZE=2][COLOR=#0000ff]New[/COLOR][/SIZE][SIZE=2] OleDbConnection("Provider=Microsoft.JET.OLEDB.4.0; data source=c:test.mdb")[/SIZE]
[SIZE=2][COLOR=#0000ff]Try[/COLOR][/SIZE]
[SIZE=2]da = [/SIZE][SIZE=2][COLOR=#0000ff]New[/COLOR][/SIZE][SIZE=2] OleDbDataAdapter("SELECT adminPW FROM Admin", conn)[/SIZE]
[SIZE=2]myDataTable = [/SIZE][SIZE=2][COLOR=#0000ff]New[/COLOR][/SIZE][SIZE=2] DataTable[/SIZE]
[SIZE=2]da.Fill(myDataSet, "Admin")[/SIZE]
[SIZE=2][COLOR=#0000ff]Catch[/COLOR][/SIZE][SIZE=2] ex [/SIZE][SIZE=2][COLOR=#0000ff]As[/COLOR][/SIZE][SIZE=2] Exception[/SIZE]
[SIZE=2]Console.WriteLine("Error Opening {0}", conn.DataSource)[/SIZE]
[SIZE=2][COLOR=#0000ff]End[/COLOR][/SIZE][SIZE=2][COLOR=#0000ff]Try[/COLOR][/SIZE]
[SIZE=2]myCommand = [/SIZE][SIZE=2][COLOR=#0000ff]New[/COLOR][/SIZE][SIZE=2] OleDbCommandBuilder(da)[/SIZE]
 
[SIZE=2][COLOR=#0000ff]Dim[/COLOR][/SIZE][SIZE=2] foundRows() [/SIZE][SIZE=2][COLOR=#0000ff]As[/COLOR][/SIZE][SIZE=2] Data.DataRow[/SIZE]
 
[SIZE=2][COLOR=#0000ff]Try[/COLOR][/SIZE]
[SIZE=2][COLOR=#008000]foundRows = something but I dont' know what to put here to get it![/COLOR][/SIZE]
[SIZE=2]myVariable= foundRows(0).Item("adminPW") [/SIZE]
 
[SIZE=2][COLOR=#0000ff]Catch[/COLOR][/SIZE]
[SIZE=2]msgbox "code is wrong"[/SIZE]
[SIZE=2][COLOR=#0000ff]End[/COLOR][/SIZE][SIZE=2][COLOR=#0000ff]Try[/COLOR][/SIZE]
 
If you are returning a single value then there is no need to use a datatable. A scalar query will do:

cmd = New OleDbCommand(existing connection)
cmd.CommandText = "SELECT onlyOneResult FROM someTable"
Dim o as Object = cmd.ExecuteScalar()

MessageBox.Show(o.ToString())

you get an object back because the query might ahve returned a date, integer, whatever.. Cast it into the correct type and off you go! if you know its a string, you can just call ToString() like i did here
 
Back
Top