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
Solved

vb.net connect to sql database and add a row

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

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
VB.NET 2008 Winforms Signing 13 31
call a controller action method from Global.asax in asp.net 1 20
Where is this file? 3 25
Code enhancement 4 21
This article describes relatively difficult and non-obvious issues that are likely to arise when creating COM class in Visual Studio and deploying it by professional MSI-authoring tools. It is assumed that the reader is already familiar with the cla…
A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
This video shows how to use Hyena, from SystemTools Software, to bulk import 100 user accounts from an external text file. View in 1080p for best video quality.

856 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