user2625202
user2625202

Reputation: 23

Insert,update and delete data from Sql database using vb.net?

This is my code for inserting data in the data table. When Execute i m getting the message "SUCCESS". But the data is not present in the data table.

Imports System.Data
Imports System.Data.SqlClient

Partial Public Class _Default
    Inherits System.Web.UI.Page
    Dim s As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=G:\ANDY\Dot Net.Practical\SQL DATA BASE\inserting4\inserting4\App_Data\location.mdf;Integrated Security=True;User Instance=True"
    Dim sql As String
    Dim con As New SqlConnection
    Dim cmd As SqlCommand

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        con = New SqlConnection(s)
        con.Open()

    End Sub

    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click

        sql = "insert into location(name,street,city)values(@name,@street,@city)"
        cmd = New SqlCommand(sql, con)

        cmd.Parameters.Add("@name", SqlDbType.NVarChar).Value = TextBox1.Text
        cmd.Parameters.Add("@street", SqlDbType.NVarChar).Value = TextBox2.Text
        cmd.Parameters.Add("@city", SqlDbType.NVarChar).Value = TextBox3.Text
        cmd.ExecuteNonQuery()

        MsgBox("SUCCESS")


    End Sub
End Class

Upvotes: 2

Views: 28557

Answers (1)

marc_s
marc_s

Reputation: 754598

The whole User Instance and AttachDbFileName= approach is flawed - at best! When running your app in Visual Studio, it will be copying around the .mdf file (from your App_Data directory to the output directory - typically .\bin\debug - where you app runs) and most likely, your INSERT works just fine - but you're just looking at the wrong .mdf file in the end!

If you want to stick with this approach, then try putting a breakpoint on the myConnection.Close() call - and then inspect the .mdf file with SQL Server Mgmt Studio Express - I'm almost certain your data is there.

The real solution in my opinion would be to

  1. install SQL Server Express (and you've already done that anyway)

  2. install SQL Server Management Studio Express

  3. create your database in SSMS Express, give it a logical name (e.g. Location)

  4. connect to it using its logical database name (given when you create it on the server) - and don't mess around with physical database files and user instances. In that case, your connection string would be something like:

    Data Source=.\\SQLEXPRESS;Database=Location;Integrated Security=True
    

    and everything else is exactly the same as before...

Upvotes: 2

Related Questions