[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Visual Studio 2005 Add data to sql DB

Posted on 2007-07-29
6
Medium Priority
?
180 Views
Last Modified: 2013-11-26
HI,

I am trying to save data to my SQL DB making use of a data class provided by a member of this forum but need some help as I get the following error:

The ConnectionString property has not been initialized.

I am using VS 2005, ASP web page with VB code.


Please see below my code:

Imports System.Data
Imports System.Data.SqlClient
Imports class1

Partial Class page1
 Inherits System.Web.UI.Page

   Protected Sub BtCreate_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtCreate.Click
        Dim SQLdatasource2 As String

        Dim conn As New SqlConnection
        SQLdatasource2 = "SELECT * from tblDetails"
        Dim cmd As New SqlCommand

        conn.Open()


        cmd = New SqlCommand(SQLdatasource2, conn)
        cmd = New SqlCommand("insert into tbldetails(adno) values(@adno)", conn)
        cmd.Parameters.Add("@adno", SqlDbType.VarChar).Value = TxtAdNo.Text

        cmd.ExecuteNonQuery()
        LblResult.Text = "Your record has been saved successfully!"
        conn.Close()
    End Sub
end class
=================================================

Imports Microsoft.VisualBasic
Imports System.Data
Imports System.Data.SqlClient

Public Class Class1
    Public Shared Function GetConnection() As SqlConnection
        Dim SqlServerName As String = "192.168.1.11"
        Dim SqlServerDatabase As String = "mydb"
        Dim SqlServerLogin As String = "Morpheus"
        Dim SqlServerPassword As String = "Nebuchadnezzar"

        Dim conn As SqlConnection

        Dim strConn As String = "Data Source=" & SqlServerName & ";Initial Catalog=" & SqlServerDatabase & ";User ID=" & SqlServerLogin & ";Password=" & SqlServerPassword & ";Integrated Security=SSPI;"

        conn = New SqlConnection(strConn)
        Try

            conn.Open()

        Catch SqlEx As SqlException
            MsgBox("Error SQL:" & vbCrLf & vbCrLf & SqlEx.Message, MsgBoxStyle.Critical)

        Catch ex As Exception
            MsgBox("Error message", MsgBoxStyle.Critical)

        End Try
        GetConnection = conn
    End Function


    <System.Diagnostics.DebuggerStepThrough()> _
    Public Shared Function ExecuteReader(ByVal query As String) As SqlDataReader
        Dim rdr As SqlDataReader = Nothing
        Dim conn As SqlConnection = GetConnection()

        Try

            Dim cmd As SqlCommand = New SqlCommand(query, conn)

            rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection)

        Catch SqlEx As SqlException
            MsgBox("Error SQL:" & vbCrLf & vbCrLf & SqlEx.Message, MsgBoxStyle.Critical)

        Catch ex As Exception
            MsgBox("Error message", MsgBoxStyle.Critical)

        End Try
        ExecuteReader = rdr
    End Function
End Class
0
Comment
Question by:neoice
  • 4
  • 2
6 Comments
 
LVL 6

Expert Comment

by:ToFro
ID: 19587666
I'm a bit confused here, you seem to have two examples of code in your question. Is one your own version and the other the "data class provided by a member of this forum"?

The first code example looks ok, but it's missing the connection string, which is found in the second example. You could add it like this:

Dim connStr As String = "the_connection_string_goes_here"
Dim conn As New SqlConnection(connStr)


... This is a good resource for connection strings: www.connectionstrings.com
0
 
LVL 6

Expert Comment

by:ToFro
ID: 19587686
Also, in the first code block, the constructor for cmd is called no more than three times (New SqlCommand):

        ...
        Dim cmd As New SqlCommand

        conn.Open()

        cmd = New SqlCommand(SQLdatasource2, conn)
        cmd = New SqlCommand("insert into tbldetails(adno) values(@adno)", conn)
        cmd.Parameters.Add("@adno", SqlDbType.VarChar).Value = TxtAdNo.Text
        ...

... When the follwing code would be enough

        ...
        Dim cmd As New SqlCommand("insert into tbldetails(adno) values(@adno)", conn)
        cmd.Parameters.Add("@adno", SqlDbType.VarChar).Value = TxtAdNo.Text
        conn.Open()
        ...
0
 
LVL 6

Expert Comment

by:ToFro
ID: 19587838
Here's the BtCreate_Click event from the first example without class1, so no need to import that.
It should insert whatever is in TxtAdNo into tbldetails(adno), assuming that the connection string is correct for your database.

Protected Sub BtCreate_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtCreate.Click

        Dim connStr As String = "Data Source=192.168.1.11;Initial Catalog=mydb;User ID=Morpheus;Password=Nebuchadnezzar;Integrated Security=SSPI;"
        Dim conn As New SqlConnection(connStr)

        Dim cmd As New SqlCommand("insert into tbldetails(adno) values(@adno)", conn)
        cmd.Parameters.Add("@adno", SqlDbType.VarChar).Value = TxtAdNo.Text

        Try
            conn.Open()
            cmd.ExecuteNonQuery()
            LblResult.Text = "Your record has been saved successfully!"

        Catch SqlEx As SqlException
            MsgBox("Error SQL:" & vbCrLf & vbCrLf & SqlEx.Message, MsgBoxStyle.Critical)

        Catch ex As Exception
            MsgBox("Error message", MsgBoxStyle.Critical)

        Finally
            conn.Close()

        End Try

    End Sub
0
Free Backup Tool for VMware and Hyper-V

Restore full virtual machine or individual guest files from 19 common file systems directly from the backup file. Schedule VM backups with PowerShell scripts. Set desired time, lean back and let the script to notify you via email upon completion.  

 

Author Comment

by:neoice
ID: 19588299
Hi ToFro,

Thanks for the reply.

The first code is my sub which I needed corrected and the second code was the connection class that I use in my web application courtesy of another user. I thought I would include it for reference. I am new to VS 2005 and web programming for that matter and this was the first attempt at DB manipulation.

Your code has worked but now I am a little confused because if I use your method, my class then becomes redundant. I would also have to include the connection string in every connection I make, which is why I thought the class procedure made sense.

Here is a snippet of code I use to populate a dropdown list box which does not require a connection string as I import the connection class:

   Protected Sub CbConsult_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles CbConsult.SelectedIndexChanged

        Dim SQLdatasource1 As String
        SQLdatasource1 = "SELECT name FROM tblconsultants where initials ='" & CbConsult.Text & "'"
         Dim dr1 As SqlDataReader = ExecuteReader(SQLdatasource1)
        While dr1.Read
            TxtConsultName.Text = dr1("name")
        End While
    End Sub

Is it not all possible to utilize the class system for writing data to the DB?

I just want to get clear in my head, a solid system for writing and reading data to and from a DB.

Thanks for your patience

Neil

0
 
LVL 6

Accepted Solution

by:
ToFro earned 2000 total points
ID: 19590245
Ok, then instead of:

Dim connStr As String = "Data Source=192.168.1.11;Initial Catalog=mydb;User ID=Morpheus;Password=Nebuchadnezzar;Integrated Security=SSPI;"
Dim conn As New SqlConnection(connStr)

...you could use this:
Dim conn As SqlConnection = Class1.GetConnection()

>> Is it not all possible to utilize the class system for writing data to the DB?
Not with the ExecuteReader method. A DataReader is an object for reading data only, one row at a time. You would have to create a new method for the class. Kind of like the one I provided for BtCreate_Click.

0
 

Author Comment

by:neoice
ID: 19594279
Ok, thanks for the advice.

neil
0

Featured Post

Prepare for your VMware VCP6-DCV exam.

Josh Coen and Jason Langer have prepared the latest edition of VCP study guide. Both authors have been working in the IT field for more than a decade, and both hold VMware certifications. This 163-page guide covers all 10 of the exam blueprint sections.

Question has a verified solution.

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

Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
We’ve all felt that sense of false security before—locking down external access to a database or component and feeling like we’ve done all we need to do to secure company data. But that feeling is fleeting. Attacks these days can happen in many w…
In a question here at Experts Exchange (https://www.experts-exchange.com/questions/29062564/Adobe-acrobat-reader-DC.html), a member asked how to create a signature in Adobe Acrobat Reader DC (the free Reader product, not the paid, full Acrobat produ…
Suggested Courses

830 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