Monday, February 20, 2012

Problem inserting data into a SQL Express database

I am trying to implement a code behind page (in VB) to insert data into a sql express database but something is not right. Any help would be greatly appreciated. The following is the code I have:

Protected Sub SaveButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles SaveButton.Click
Dim connString As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\News.mdf;Integrated Security=True;User Instance=True;Asynchronous Processing=true"
Dim sqlInsert As String = "INSERT INTO news_Article (Heading, Story, Author, Show_on_homepage) VALUES(@.heading, @.story, @.author, @.show)"
Dim conn As New System.Data.SqlClient.SqlConnection(connString)
Dim cmd As New System.Data.SqlClient.SqlCommand(sqlInsert, conn)
Dim heading = HeadingTextBox.Text
Dim story = StoryEditor.Value
Dim author = AuthorTextBox.Text
Dim show = ShowHPCheckBox.Checked

conn.Open()
cmd.BeginExecuteNonQuery()
conn.Close()

End Sub

Instead of
Dim heading = HeadingTextBox.Text

Do
cmd.Parameters.AddWithValue("@.heading", HeadingTextBox.Text)

Happy coding!

|||Cheers for the quick reply. I tried what you suggested but it is still not going into the database. Back to the drawing board I goConfused|||

Hi Dragpop,

I agree with Mikael that you need to use

cmd.Parameters.AddWithValue("@.heading", HeadingTextBox.Text)

for each parameter. Also, when you're trying to execute it, you need to use cmd.ExecuteNonQuery(), since cmd.BeginExecuteNonQuery() is for asynchronous execution.

HTH. If this does not answer you question, please feel free to mark it as Not Answered and post your reply. Thanks!

|||

Cheers for the advise Kevin. I have it all sorted now and is working great.

No comments:

Post a Comment