I wrote code to insert TextBox data into SQL database. My code working properly but when I open the table no data was added. Here is my code:
Private Sub save_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles save.Click
Dim connetionString As String
Dim connection As SqlConnection
Dim adapter As New SqlDataAdapter
Dim tabl As New DataTable
Dim sql As String
connetionString = "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True"
connection = New SqlConnection(connetionString)
Try开发者_JAVA百科
sql = "insert into model (no,fistname,lastname) values('" & TextBox1.Text & "','" & TextBox2.Text & "','" & TextBox3.Text & "')"
adapter.InsertCommand = New SqlCommand(sql, connection)
connection.Open()
adapter.InsertCommand.ExecuteNonQuery()
MsgBox("Row inserted !! ")
connection.Close()
Catch ex As Exception
MsgBox(ex.ToString)
connection.Close()
End Try
End Sub
Don't use a Data Adapter. That just over-complicates things in this case. Try:
Using SqlConnection connection = new SqlConnection(connectionString)
sql = "insert into model (no, firstname, lastname)" & _
" values (@val1, @val2, @val3)"
Dim SqlCommand command = new SqlCommand(sql, connection)
command.Parameters.Add("val1", TextBox1.Text)
command.Parameters.Add("val2", TextBox2.Text)
command.Parameters.Add("val3", TextBox3.Text)
command.ExecuteNonQuery()
End Using
This way, you don't have to worry about the Adapter (since you're not using a GridView) and you're using parameterized queries rather than dynamically building SQL (which allows for SQL Injection attacks).
I'll go way out on a limb here — I'm not even sure what language that is — and suggest that perhaps you need to explicitly commit your database transaction.
How do you confirm that the data was not inserted?
I suspect your issue may be related to using User Instances of SQL Express. See http://msdn.microsoft.com/en-us/library/bb264564%28SQL.90%29.aspx
精彩评论