2012-03-13 113 views
0

我需要一个简单的程序,它可以添加,编辑,保存,删除vb.net数据库中的数据。我已经尝试过数据集或sqlcommandbuilder,但两者都不起作用。 请看看我用过的sqlcommandbuilder的代码,它没有在数据库中保存任何东西。 请提供最简单的方法将数据从数据集或直接从文本框保存到数据库中。 在此vb.net没有显示任何错误,但不保存无法保存vb.net数据库中的数据

'set up a connection string' 
Dim connectionstring As String 

connectionstring = "Data Source=|DataDirectory|\inventorymanage.sdf;Password='XXX'" 

Dim sqlquery As String = "SELECT * FROM ledger" 

'create connection' 
Dim connaction As SqlCeConnection = New SqlCeConnection(connectionstring) 

Try 
    'open connection' 
    connaction.Open() 



    'create data adapter' 
    Dim da As SqlCeDataAdapter = New SqlCeDataAdapter(sqlquery, connaction) 

    'create command builder' 
    Dim commandbuilder As SqlCeCommandBuilder = New SqlCeCommandBuilder(da) 


    'create dataset' 
    Dim ds As New DataSet 

    'fill dataset' 
    da.Fill(ds, "ledger") 

    'get datatable' 
    Dim dt As DataTable = ds.Tables("ledger") 

    Dim dsnewrow As DataRow 

    dsnewrow = ds.Tables("ledger").NewRow() 



    ds.Tables("ledger").Rows.Add(dsnewrow) 
    With dt 
     ' modify data rows in ledger 
     .Rows(0).Item(1) = Textbox4.Text 
     .Rows(0).Item(2) = TextBox5.Text 
    End With 



    da.Update(ds, "ledger") 


    MsgBox("record added") 
Catch ex As SqlCeException 
    MsgBox("you got error" & ex.ToString & vbCrLf) 

Finally 
    'close connection' 
    connaction.Close() 
End Try 

回答

0

你不应该AddDataRowDataTable,直到你完成它:

Dim newRow As DataRow = ds.Tables("ledger").NewRow 
newRow(1) = Textbox4.Text ' set the value for the second field ' 
newRow(2) = Textbox2.Text ' set the value for the third field ' 
ds.Tables("ledger").Rows.Add(newRow) 
da.Update(ds, "ledger") 

http://msdn.microsoft.com/en-us/library/5ycd1034%28v=vs.100%29.aspx

编辑:虽然我必须承认,订单不应该很重要,但为什么你使用Dim dt As DataTable = ds.Tables("ledger")呢?这只是令人困惑,因为你实际上并不需要它。

+0

使用您的代码后,我仍然无法保存数据库中的数据。我正在使用sql server compact3.5。 – 2012-03-13 15:00:04

+0

你看过这里吗? http://stackoverflow.com/questions/3223359/cant-get-sql-server-compact-3-5-4-to-work-with-asp-net-mvc-2 – 2012-03-13 15:14:41

0
Dim con As New OleDb.OleDbConnection 
Dim sql As String 
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 
    con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\CMS.mdb" 
    con.Open() 
    sql = "insert into tblStaffType (Staff_Type,Code) VALUES (@Staff_Type,@Code)" 
    Dim command = New OleDb.OleDbCommand(sql, con) 
    command.Parameters.AddWithValue("@staff_type", txtTypName.Text) 
    command.Parameters.AddWithValue("@Code", txtTypCde.Text) 
    command.ExecuteNonQuery() 
    con.Close() 
    MsgBox("saved") 
End Sub