VB.Net SQL Databases- How to Save Changes to Database?
My database program is fully functional and when I add new entries to the database they appear on my DataGridView correctly. However after I close the program these changes are not saved. How do I save the changes back to the database? Here's my code:
Dim conn As New SqlClient.SqlConnection(My.Settings.MainDatabaseConnectionString)
Dim query As String = "INSERT INTO Users VALUES('Something','Test');"
Dim cmd As New SqlClient.SqlCommand(query, conn)
开发者_如何学编程 Dim reader As SqlClient.SqlDataReader
'Open Connection
conn.Open()
'Execute Query
reader = cmd.ExecuteReader
'Close Connection
conn.Close()
'Update DataGridView
Me.UsersTableAdapter.Fill(Me.UsersDataSet.Users)
As you've discovered, you need more the a reader :)
There are many ways to go. This link gives a reasonable example:
http://msdn.microsoft.com/en-us/library/ms972948.aspx
The key thing:
To start, the GridView's SqlDataSource must contain an UpdateCommand with appropriate parameters.
If you want to insert something into the DB you can do this
Dim mySQLCommand As Data.SqlClient.SqlCommand
mySQLCommand.CommandText = "INSERT INTO Users VALUES('Something','Test');"
mySQLCommand.ExecuteNonQuery()
you might also want to parameterize your variables to prevent sql injections
mySQLCommand.Parameters.Add("@variable_name", SqlDBType.NvarChar).value = variable
and using @variable_name
in the insert
mySQLCommand.CommandText = INSERT INTO Users VALUES(@variable_name, @variable_name2)
精彩评论