473,806 Members | 2,330 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Reading one record from an Access DB

I've started some code but do not know how to get the anwser. Here is the
code:

I need the first four characters of data in a field (TextName) to get a name
from a DB and put the name back into TextName.

Dim conn As New
System.Data.Ole Db.OleDbConnect ion("Provider=M icrosoft.Jet.OL EDB.4.0;Data
source=C:\BMAct ivityReporting. mdb;Persist Security Info=False")

Dim sSQL As String = "select * from User Where UserNo=" & Mid(TextName.Te xt,
1, 4)

conn.Open()

Dim da As New System.Data.Ole Db.OleDbDataAda pter(sSQL, conn)

Try

TextName.Text = da.

I do not know how to finish or if I'm headed in the right direction.

THanks,

Steve
Jul 13 '06 #1
10 3958
DataAdapter is overkill for what you want.
You want a Command object, in this case, OleDbCommand.
You want to use the ExecuteScalar() method.

Jul 13 '06 #2
I think I set everything up ok.

Here is the string for the SQL statement take while watching in the
debugger:

"select * from User Where UserNo='0000'"

There is a record with UserNo='0000' (Text type) in a table User.

the da.ExecuteScala r() completes within a Try..

I do not know how to get the value for the exeption; there is an execption.

How do I get the value for the exception?

THanks,

Steve
"Steven Nagy" <le*********@ho tmail.comwrote in message
news:11******** **************@ m73g2000cwd.goo glegroups.com.. .
DataAdapter is overkill for what you want.
You want a Command object, in this case, OleDbCommand.
You want to use the ExecuteScalar() method.

Jul 13 '06 #3
OK, I'm exceited.

I figured out how to get the exception to a msgbox.

I'm getting an error in the FROM Clause.

Hopefully I figure that out:)

If someone has an idea let me know.

THanks,
Steve
"Stephen Plotnick" <sp*******@grou pcbf.comwrote in message
news:va******** *************** *******@giganew s.com...
>I think I set everything up ok.

Here is the string for the SQL statement take while watching in the
debugger:

"select * from User Where UserNo='0000'"

There is a record with UserNo='0000' (Text type) in a table User.

the da.ExecuteScala r() completes within a Try..

I do not know how to get the value for the exeption; there is an
execption.

How do I get the value for the exception?

THanks,

Steve
"Steven Nagy" <le*********@ho tmail.comwrote in message
news:11******** **************@ m73g2000cwd.goo glegroups.com.. .
>DataAdapter is overkill for what you want.
You want a Command object, in this case, OleDbCommand.
You want to use the ExecuteScalar() method.


Jul 13 '06 #4
Ok the 'ExecuteScalar' method only returns a single value.
But you are doing a SELECT * which means return all columns for that
row.
This also means that more than one value is being returned.
So you need firstly only select the column in question.

Also, post the error message here so we can see the problem.

And post your code too

Stephen Plotnick wrote:
OK, I'm exceited.

I figured out how to get the exception to a msgbox.

I'm getting an error in the FROM Clause.

Hopefully I figure that out:)

If someone has an idea let me know.

THanks,
Steve
"Stephen Plotnick" <sp*******@grou pcbf.comwrote in message
news:va******** *************** *******@giganew s.com...
I think I set everything up ok.

Here is the string for the SQL statement take while watching in the
debugger:

"select * from User Where UserNo='0000'"

There is a record with UserNo='0000' (Text type) in a table User.

the da.ExecuteScala r() completes within a Try..

I do not know how to get the value for the exeption; there is an
execption.

How do I get the value for the exception?

THanks,

Steve
"Steven Nagy" <le*********@ho tmail.comwrote in message
news:11******** **************@ m73g2000cwd.goo glegroups.com.. .
DataAdapter is overkill for what you want.
You want a Command object, in this case, OleDbCommand.
You want to use the ExecuteScalar() method.
Jul 13 '06 #5
I changed to get only one field Username and still get the following error:

Index #0
Message: Syntax error in FROM clause
NativeError: -526650802
Source: Miscrofosft JET Database Engine
SQLState: 3000

Dim conn As New
System.Data.Ole Db.OleDbConnect ion("Provider=M icrosoft.Jet.OL EDB.4.0;Data
source=C:\BMAct ivityReporting. mdb;Persist Security Info=False")

Dim sSQL As String = "select UserName FROM User WHERE UserNo='" &
Mid(TextName.Te xt, 1, 4) & "'"

Dim da As New System.Data.Ole Db.OleDbCommand (sSQL, conn)

conn.Open()

Try

da.ExecuteScala r()

'StringResult = myCommand.Execu teScalar ( );

' TextName.Text = da.

Catch ex As System.Data.Ole Db.OleDbExcepti on

Dim errorMessages As String

Dim i As Integer

For i = 0 To ex.Errors.Count - 1

errorMessages += "Index #" & i.ToString() & ControlChars.Cr _

& "Message: " & ex.Errors(i).Me ssage & ControlChars.Cr _

& "NativeErro r: " & ex.Errors(i).Na tiveError & ControlChars.Cr _

& "Source: " & ex.Errors(i).So urce & ControlChars.Cr _

& "SQLState: " & ex.Errors(i).SQ LState & ControlChars.Cr

Next i

MsgBox(errorMes sages)

Finally

conn.Close()

End Try
"Steven Nagy" <le*********@ho tmail.comwrote in message
news:11******** **************@ 35g2000cwc.goog legroups.com...
Ok the 'ExecuteScalar' method only returns a single value.
But you are doing a SELECT * which means return all columns for that
row.
This also means that more than one value is being returned.
So you need firstly only select the column in question.

Also, post the error message here so we can see the problem.

And post your code too

Stephen Plotnick wrote:
>OK, I'm exceited.

I figured out how to get the exception to a msgbox.

I'm getting an error in the FROM Clause.

Hopefully I figure that out:)

If someone has an idea let me know.

THanks,
Steve
"Stephen Plotnick" <sp*******@grou pcbf.comwrote in message
news:va******* *************** ********@gigane ws.com...
>I think I set everything up ok.

Here is the string for the SQL statement take while watching in the
debugger:

"select * from User Where UserNo='0000'"

There is a record with UserNo='0000' (Text type) in a table User.

the da.ExecuteScala r() completes within a Try..

I do not know how to get the value for the exeption; there is an
execption.

How do I get the value for the exception?

THanks,

Steve
"Steven Nagy" <le*********@ho tmail.comwrote in message
news:11******** **************@ m73g2000cwd.goo glegroups.com.. .
DataAdapter is overkill for what you want.
You want a Command object, in this case, OleDbCommand.
You want to use the ExecuteScalar() method.

Jul 13 '06 #6
Stephen,

Okay, I usually do SQL Server, so some of this is specific to that.

I would use a datareader.

Here is a function that I use for it.

Place the following function in a VB class called DHOleDB (Data
Handler).

Public Shared Function GetDataReader( _
ByVal strSQL as String, _
ByVal strCN as String) AS OleDbDataReader
Dim dr as OleDbDataReader
Dim cmd as New OleDbCommand
With cmd
.Connection = New OleDbConnection (strCN)
.Connection.Ope n()
.CommandText = strSQL
dr = .ExecuteReader( CommandBehavior .CloseConnectio n)
End With
Return dr
End Function

Call this using your connection string and SQL string using the
following code:

dim dr as OleDbDataReader
dr = DHOleDB.GetData Reader(your sql string, your connection string)
If dr.read then
..... Do what you want to here i.e.
StringResult = dr("UserNo")
End if
dr.close

Stephen Plotnick wrote:
I changed to get only one field Username and still get the following error:

Index #0
Message: Syntax error in FROM clause
NativeError: -526650802
Source: Miscrofosft JET Database Engine
SQLState: 3000

Dim conn As New
System.Data.Ole Db.OleDbConnect ion("Provider=M icrosoft.Jet.OL EDB.4.0;Data
source=C:\BMAct ivityReporting. mdb;Persist Security Info=False")

Dim sSQL As String = "select UserName FROM User WHERE UserNo='" &
Mid(TextName.Te xt, 1, 4) & "'"

Dim da As New System.Data.Ole Db.OleDbCommand (sSQL, conn)

conn.Open()

Try

da.ExecuteScala r()

'StringResult = myCommand.Execu teScalar ( );

' TextName.Text = da.

Catch ex As System.Data.Ole Db.OleDbExcepti on

Dim errorMessages As String

Dim i As Integer

For i = 0 To ex.Errors.Count - 1

errorMessages += "Index #" & i.ToString() & ControlChars.Cr _

& "Message: " & ex.Errors(i).Me ssage & ControlChars.Cr _

& "NativeErro r: " & ex.Errors(i).Na tiveError & ControlChars.Cr _

& "Source: " & ex.Errors(i).So urce & ControlChars.Cr _

& "SQLState: " & ex.Errors(i).SQ LState & ControlChars.Cr

Next i

MsgBox(errorMes sages)

Finally

conn.Close()

End Try
"Steven Nagy" <le*********@ho tmail.comwrote in message
news:11******** **************@ 35g2000cwc.goog legroups.com...
Ok the 'ExecuteScalar' method only returns a single value.
But you are doing a SELECT * which means return all columns for that
row.
This also means that more than one value is being returned.
So you need firstly only select the column in question.

Also, post the error message here so we can see the problem.

And post your code too

Stephen Plotnick wrote:
OK, I'm exceited.

I figured out how to get the exception to a msgbox.

I'm getting an error in the FROM Clause.

Hopefully I figure that out:)

If someone has an idea let me know.

THanks,
Steve
"Stephen Plotnick" <sp*******@grou pcbf.comwrote in message
news:va******** *************** *******@giganew s.com...
I think I set everything up ok.

Here is the string for the SQL statement take while watching in the
debugger:

"select * from User Where UserNo='0000'"

There is a record with UserNo='0000' (Text type) in a table User.

the da.ExecuteScala r() completes within a Try..

I do not know how to get the value for the exeption; there is an
execption.

How do I get the value for the exception?

THanks,

Steve
"Steven Nagy" <le*********@ho tmail.comwrote in message
news:11******** **************@ m73g2000cwd.goo glegroups.com.. .
DataAdapter is overkill for what you want.
You want a Command object, in this case, OleDbCommand.
You want to use the ExecuteScalar() method.

Jul 13 '06 #7
Ignore Raibert... Data Adapter is too much fluff for returning a single
value.

The syntax error indicates that there is an error in your SQL.
Double check that the column and table names are correct.
Also, put square brackets around the User part in the from clause.
Ie. [User]
In sql server, User is a reserved word. I am not sure if this is the
same in Access but it might help.

Also, the execute scalar method returns a value, so you should assign
its output to your textbox.text or whatever you want to do with it.

For debugging, you can also try running your query in access directly
to see if it works.
It might provide more helpful debug information.

Jul 13 '06 #8
Steve,

I changed the table name from User to UserTable and it works great.

I do like the concept from Raibert for developing an I/O module (class) for
the data base.

Short story; I've been programming in COBOL since finishing school in 1981
and decided to toy with VB.NET for a client's project I started a couple of
weeks ago. I was able to do a da.fill to a datagrid and pull data through a
dataviewrow to 8 screens and uddate 84 variables that can be changed. I was
amazed I accomplished this. Now when I wanted one field from one record I
was stumped, I thank you for getting me through that so easily.

In COBOL and ODBC I wrote I/O modules that did every SQL command possible.
I'm going to try this when I get a break.

Thanks for all the help,
Steve
"Steven Nagy" <le*********@ho tmail.comwrote in message
news:11******** **************@ p79g2000cwp.goo glegroups.com.. .
Ignore Raibert... Data Adapter is too much fluff for returning a single
value.

The syntax error indicates that there is an error in your SQL.
Double check that the column and table names are correct.
Also, put square brackets around the User part in the from clause.
Ie. [User]
In sql server, User is a reserved word. I am not sure if this is the
same in Access but it might help.

Also, the execute scalar method returns a value, so you should assign
its output to your textbox.text or whatever you want to do with it.

For debugging, you can also try running your query in access directly
to see if it works.
It might provide more helpful debug information.

Jul 14 '06 #9
Its definately a good idea but also consider some other tools to help
you with the process. Code generation is a very powerful way of
creating code that exhibits repetitive nature.

For example, say you have 50 tables in your database. You want to
create a nice module for each table that has basic Create, Retrieve,
Update, and Delete functionality in your VB.NET application. Code
generation tools such as CodeSmith can help with this. I wrote my own
code generater 3 or 4 years ago which I am now over hauling with
CodeSmith for creating my Data connection layer. Currently it generates
about 400 lines of code per table in useful methods for interacting
with that table. It even can do things like check for Foreign keys in a
table and create "Select" statements based on those foreign keys. This
is the power of code generation. It also creates a "Standard" for the
methods interacting with your tables. Eg. My tables 'Person' and
'Salary' both have had code generated for them from my code generator.
Now I have a 'Person' class that has a 'Create' method, and I have a
'Salary' class that also has a 'Create' method, but they each have
different argument lists.

Visual Studio even makes use of code generators. When you create some
visual elements in design mode, it uses an in-built code generater to
create the code for those controls. Or when you use dataAdapters to
create datasets in design mode, once again a class is created that
contains an xml description of your dataset. This is autogenerated as
well, and the code that goes with that xml is generated FROM the xml
also.

Also of interest when it comes to database programming, is the
Application Blocks that are downloadable as a part of the Enterprise
Library from Microsoft. Its not an officially supported Microsoft
product, but it is a download on their site. There is an Application
Block related to data access that will help make connecting to
databases easier and less code intensive. This might be a consideration
for you.

Hope this helps.

Jul 14 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
3406
by: muser | last post by:
With the following code I'm trying to read a text file (infile) and output inaccuracies to the error file (printerfile). The text file is written and stored on disk, while the printerfile has to be created when the program executes. But the compile keeps reading that it can't find the text file. Karl you wrote the original program from which this one is but a poor copy, can you or anyone else enlighten me as to why yours worked and mine...
1
1933
by: muser | last post by:
The following program reads two lines of a file in my A drive and reads no more. Can some sarmartian tell me why that is. Please copy and paste the program into your own compiler please. program is this. #include <iostream> #include <iomanip> #include <fstream>
2
1960
by: Hutton | last post by:
This code works fine, the Windows regional settings are UK (dd/mm/yyyy) but when it reads the record set it recognises them as US dates - mm/dd/yyyy. All dates are formatted as short dates. Would like to know how to overcome this and why it does it. Public Function HowDays(StartDate As Date, EndDate As Date) As Integer 'Get the number of workdays between the given dates
15
2153
by: shaqattack1992-newsgroups | last post by:
Hello Everyone, Let me explain my problem. I have included 2 dashes between each pair of records to make it easier to see what goes together. In reality, it is just a long list of results from my query. Contract--------QTY--------COMPONENT--------LENGTH-------PCS
8
9539
by: Yeow | last post by:
hello, i was trying to use the fread function on SunOS and ran into some trouble. i made a simple test as follows: i'm trying to read in a binary file (generated from a fortran code) that contains the following three floating-point numbers: 1.0 2.0 3.0
6
3800
by: KevinD | last post by:
assumption: I am new to C and old to COBOL I have been reading a lot (self teaching) but something is not sinking in with respect to reading a simple file - one record at a time. Using C, I am trying to read a flatfile. In COBOL, my simple file layout and READ statement would look like below. Question: what is the standard, simple coding convention for reading in a flatfile - one record at a time?? SCANF does not work because of...
4
8374
by: Jason Kumpf | last post by:
OK I've been staring at this code all day and still with everything I have tried I cannot figure out two problems I am having. Once is why the space limit for the directory I create in the code fails. Second, why the data reader is reading every other record. Here is all of the source code for my little application followed by the contents of the log file that it dumps out:...
1
8771
by: vadarv | last post by:
Hia! I'm a total amateur to VBS but need help on a VBS script. This is used in a HMI system from Siemens called WinCC, used for process viewing and control. What I need to is to write to a table in Access, then read these values and then delete records (rows) in Access. By using help functions in WinCC I have this set up: I created an Access database with the WINCC_DATA table and columns (ID, TagValue) with the ID as the Auto Value. ...
23
2002
by: cyclops | last post by:
Hi All, I am working on this project which requries making a product by adding one of 7 types of components (each type of component in turn has many variations). product is made of about 25 components. the purpose of this project is to make a record of each item that has gone into making of each product. I have created 7 tables for maintaining record of each type of component (which has 23 fields each) and there is a master table which will...
1
1665
by: Barfy the Wonder Camel | last post by:
I've loaded a dataset from an access database, and now I want to find a specific record in a datatable that's part of that dataset. First, I was surprised to find that the Find() method complains that there's no primary key on the datatable, even though I've checked 3 times that there is a primary key on the access table. So either Access PKs don't translate well, or you always have to explicitly define the PKs in a datatable after reading...
0
9719
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9597
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
10371
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10110
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9187
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6877
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5546
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5678
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4329
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.