2011-07-22 165 views
0

我的數據庫程序功能齊全,當我向數據庫添加新條目時,它們正確顯示在我的DataGridView上。但是,關閉程序後,這些更改不會保存。如何將更改保存回數據庫?這裏是我的代碼:VB.Net SQL數據庫 - 如何保存對數據庫的更改?

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) 

回答

0

如果要插入一些內容數據庫,你可以做到這一點

Dim mySQLCommand As Data.SqlClient.SqlCommand 
mySQLCommand.CommandText = "INSERT INTO Users VALUES('Something','Test');" 
mySQLCommand.ExecuteNonQuery() 

,你可能還需要參數的變量,以防止SQL注入

mySQLCommand.Parameters.Add("@variable_name", SqlDBType.NvarChar).value = variable 

,並在使用@variable_name插入

mySQLCommand.CommandText = INSERT INTO Users VALUES(@variable_name, @variable_name2)