1

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
1
  • 2
    you query is prone of sql injection. Commented Feb 16, 2013 at 17:31

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.