Solved

vb.net connect to sql database and add a row

Posted on 2003-11-13
4
1,812 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
  • 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

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

Suggested Solutions

In my previous article (http://www.experts-exchange.com/Programming/Languages/.NET/.NET_Framework_3.x/A_4362-Serialization-in-NET-1.html) we saw the basics of serialization and how types/objects can be serialized to Binary format. In this blog we wi…
This document covers how to connect to SQL Server and browse its contents.  It is meant for those new to Visual Studio and/or working with Microsoft SQL Server.  It is not a guide to building SQL Server database connections in your code.  This is mo…
This video discusses moving either the default database or any database to a new volume.
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.

705 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

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now