Solved

vb.net connect to sql database and add a row

Posted on 2003-11-13
4
1,821 Views
Last Modified: 2008-09-12
Hi,

This is my first vb .net project, so it's probably something simple.
When my code runs, I get the following error. (code pasted below)
The example was taken from msdn.

Thanks for any help offered.

The Error
-------------------------------------------------------------------------------------------------------------------------------

An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in system.data.dll

Additional information: System error.
--------------------------------------------------------------------------------------------------------------------------------
'Start of code
        'ADD TO DB


        Dim sConnectionString As String


        ' Modify the following code to correctly connect to your SQL Server.
        sConnectionString = "Password=cue;User ID=cue;" & _
                            "Initial Catalog=Cue;" & _
                            "Data Source=pd100408"


        Dim objConn As New SqlConnection(sConnectionString)
        objConn.Open()

        ' Create an instance of a DataAdapter.
        Dim da As _
            New SqlDataAdapter("Select * From DH51", objConn)

        ' Create an instance of a DataSet, and retrieve data from the DH51 table.
        Dim ds As New DataSet("DH51")
        da.FillSchema(ds, SchemaType.Source, "DH51")
        da.Fill(ds, "DH51")

        '*****************
        'BEGIN ADD CODE
        ' Create a new instance of a DataTable.
        Dim tblDH51 As DataTable
        tblDH51 = ds.Tables("DH51")

        Dim drCurrent As DataRow
        ' Obtain a new DataRow object from the DataTable.
        drCurrent = tblDH51.NewRow()

        ' Set the DataRow field values as necessary.

        drCurrent("Unit Number") = strUnitNumber
        drCurrent("Enquiry Type") = strEnquiryType
        drCurrent("Record Type") = strRecordType
        'drCurrent("Report Usage") =
        drCurrent("Processing Status") = strProcessingStatus
        drCurrent("Creation Date") = strCreationDate
        drCurrent("Creation Time") = strCreationTime
        drCurrent("Cue Reference Number") = strCueReferenceNumber

        'Pass that new object into the Add method of the DataTable.Rows collection.
        tblDH51.Rows.Add(drCurrent)
        'MsgBox("Add was successful.")

        'END ADD CODE


        '*****************
        'BEGIN SEND CHANGES TO SQL SERVER

        Dim objCommandBuilder As New SqlCommandBuilder(da)
        da.Update(ds, "DH51")

        '07979 906888
        MsgBox("SQL Server updated successfully" & Chr(13) & "Check Server explorer to see changes")

        ' END SEND CHANGES TO SQL SERVER
0
Comment
Question by:andy_booth
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
4 Comments
 
LVL 1

Author Comment

by:andy_booth
ID: 9740110
Oops for to say, the line it falls over on is...

da.Update(ds, "DH51")
0
 
LVL 44

Expert Comment

by:Arthur_Wood
ID: 9740455
you may need to make a single 'small' addition:

 Dim da As _
            New SqlDataAdapter("Select * From DH51", objConn)
 da.InsertCommand = new SQLCommand("Insert into DH51 (Unit Numner, Enquiry Type,Record Type,Processing Status,Creation Date,Creation Time,Cue Reference Number) VALUES(@UnitNumber, @EnquiryType,@RecordType,@ProcessingStatus,@CreationDate,@CreationTime,@CueReferenceNumber), objConn)
Dim workParm as sqlParameter

workParm = da.InsertCommand.Parameters.Add(New sqlParmeter("@UnitNumber",sqlDbType.Int))
workParm.SourceColumn = "Unit Number"
workParm.SourceVersion = DataRowVersion.Current

workParm = da.InsertCommand.Parameters.Add(New sqlParmeter("@EnquiryType",sqlDbType.Int)) ' or whatever type is relevant
workParm.SourceColumn = "Enquiry Type"
workParm.SourceVersion = DataRowVersion.Current

workParm = da.InsertCommand.Parameters.Add(New sqlParmeter("@RecordType",sqlDbType.Int)) ' or whatever type is relevant
workParm.SourceColumn = "Record Type"
workParm.SourceVersion = DataRowVersion.Current

workParm = da.InsertCommand.Parameters.Add(New sqlParmeter("@ProcessingStatus",sqlDbType.Int)) ' or whatever type is relevant
workParm.SourceColumn = "Processing Status"
workParm.SourceVersion = DataRowVersion.Current

and so on for each of the fields in the record.

notice that it is a VERY VERY bad idea to have embeddied BLANKS in the names of either Tbales or Fields---  rename the Field "Unit Number' to either "UnitNumber" or "Unit_Number".

AW



0
 
LVL 44

Expert Comment

by:Arthur_Wood
ID: 9740482
you should use the DataAdaper WIZARD for the first couple of applications, as it will build all of the UGLY code that you see above, for you, to build the necessary INSERT,DELETE and UPDATE commands for the DataAdapter.

AW
0
 
LVL 4

Accepted Solution

by:
krznpsk earned 250 total points
ID: 9744424
Andy,

The code looks fine to me; the error is clearly occurring in your SqlConnection.

In case you didn't know, the DataAdapter object will implicitly OPEN your SqlConnection object, then CLOSE it when it's done with the Fill() method.

Anyway, the problem is kind of hard to identify right now because you're not really seeing the error message.  Do you know about Try/Catch blocks?  You should place your code in a Try/Catch so that you can at least see a more detailed error message.

Here is your code rewritten in a Try/Catch block... you'll see the only changes are one line at the top and three at the bottom.  Good luck!:

Try
        Dim sConnectionString As String


        ' Modify the following code to correctly connect to your SQL Server.
        sConnectionString = "Password=cue;User ID=cue;" & _
                            "Initial Catalog=Cue;" & _
                            "Data Source=pd100408"


        Dim objConn As New SqlConnection(sConnectionString)
        objConn.Open()

        ' Create an instance of a DataAdapter.
        Dim da As _
            New SqlDataAdapter("Select * From DH51", objConn)

        ' Create an instance of a DataSet, and retrieve data from the DH51 table.
        Dim ds As New DataSet("DH51")
        da.FillSchema(ds, SchemaType.Source, "DH51")
        da.Fill(ds, "DH51")

        '*****************
        'BEGIN ADD CODE
        ' Create a new instance of a DataTable.
        Dim tblDH51 As DataTable
        tblDH51 = ds.Tables("DH51")

        Dim drCurrent As DataRow
        ' Obtain a new DataRow object from the DataTable.
        drCurrent = tblDH51.NewRow()

        ' Set the DataRow field values as necessary.

        drCurrent("Unit Number") = strUnitNumber
        drCurrent("Enquiry Type") = strEnquiryType
        drCurrent("Record Type") = strRecordType
        'drCurrent("Report Usage") =
        drCurrent("Processing Status") = strProcessingStatus
        drCurrent("Creation Date") = strCreationDate
        drCurrent("Creation Time") = strCreationTime
        drCurrent("Cue Reference Number") = strCueReferenceNumber

        'Pass that new object into the Add method of the DataTable.Rows collection.
        tblDH51.Rows.Add(drCurrent)
        'MsgBox("Add was successful.")

        'END ADD CODE


        '*****************
        'BEGIN SEND CHANGES TO SQL SERVER

        Dim objCommandBuilder As New SqlCommandBuilder(da)
        da.Update(ds, "DH51")

        '07979 906888
        MsgBox("SQL Server updated successfully" & Chr(13) & "Check Server explorer to see changes")

        ' END SEND CHANGES TO SQL SERVER

Catch ex as Exception
        messagebox.show(ex.message)
End Try
0

Featured Post

Learn by Doing. Anytime. Anywhere.

Do you like to learn by doing?
Our labs and exercises give you the chance to do just that: Learn by performing actions on real environments.

Hands-on, scenario-based labs give you experience on real environments provided by us so you don't have to worry about breaking anything.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Summary Displaying images in RichTextBox is a common requirement with limited solutions available. Pasting through clipboard or embedding into RTF content only support static images.  This article describes how to insert Windows control objects int…
Welcome my friends to the second instalment and follow-up to our Minify and Concatenate Your Scripts and Stylesheets (http://www.experts-exchange.com/Programming/Languages/.NET/ASP.NET/A_4334-Minify-and-Concatenate-Your-Scripts-and-Stylesheets.html)…
If you're a developer or IT admin, you’re probably tasked with managing multiple websites, servers, applications, and levels of security on a daily basis. While this can be extremely time consuming, it can also be frustrating when systems aren't wor…
Michael from AdRem Software outlines event notifications and Automatic Corrective Actions in network monitoring. Automatic Corrective Actions are scripts, which can automatically run upon discovery of a certain undesirable condition in your network.…

717 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question