user2078884
user2078884

Reputation: 11

Need to save data in sql database using vb8 express

I need to save data that is entered at run time. How do I do that? I tried lots of codes. I do not get any errors in my code, but the data is not present in the database when I exit and check my data table.

Here is my code:

Dim con As New SqlClient.SqlConnection
Dim cmd As New SqlClient.SqlCommand

Try
    con.ConnectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirector y|\ClubDatabase.mdf;Integrated Security=True;User Instance=True"
    con.Open()
    cmd.Connection = con
    cmd.CommandText = "INSERT INTO Liquor([Product ID], [Name], [Quantity], [Cost Price], [Selling Price]) VALUES('" & Product_IDTextBox.Text & "','" & NameTextBox.Text & "','" & QuantityTextBox.Text & "','" & Cost_PriceTextBox.Text & "','" & Selling_PriceTextBox.Text & "')"
    cmd.ExecuteNonQuery()
    MessageBox.Show("added")
Catch ex As Exception
    MessageBox.Show("Error while inserting record on table..." & ex.Message, "Insert Records")
Finally
    con.Close()
End Try

Upvotes: 1

Views: 963

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. ClubDatabase)

  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=ClubDatabase;Integrated Security=True
    

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

Upvotes: 1

Related Questions