在MS ACCESS表中创建新记录

时间:2014-08-12 12:45:01

标签: vb.net ms-access

我正在尝试创建一个从vb.net到msaccess表的新记录,我可以这样做,但我必须添加下一个连续的ID号才能实际保存。例如,如果Access DB中的下一个ID是4,我必须在表单上的id文本字段中键入4。代码如下:

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    Dim sqlinsert As String
    ' We use the INSERT statement which tells our program to add the information  
    ' from the Forms Text fields into the Databases columns.   
    sqlinsert = "INSERT INTO Table1(Title, YearofFilm, Description, Field1, ID)" & _
    "VALUES(@Title, @YearofFilm, @Description, @Field1, @ID)"
    Dim cmd As New OleDbCommand(sqlinsert, con1)
    ' This assigns the values for our columns in the DataBase.   
    ' To ensure the correct values are written to the correct column  
    cmd.Parameters.Add(New OleDbParameter("@Title", TextBox1.Text))
    cmd.Parameters.Add(New OleDbParameter("@YearofFilm", Convert.ToInt32(TextBox2.Text)))
    cmd.Parameters.Add(New OleDbParameter("@Description", TextBox3.Text))
    cmd.Parameters.Add(New OleDbParameter("@Field1", TextBox4.Text))
    cmd.Parameters.Add(New OleDbParameter("@ID", Convert.ToInt32(TextBox5.Text)))
    ' This is what actually writes our changes to the DataBase.  
    ' You have to open the connection, execute the commands and  
    ' then close connection.  
    con1.Open()
    cmd.ExecuteNonQuery()
    con1.Close()
    ' This are subs in Module1, to clear all the TextBoxes on the form  
    ' and refresh the DataGridView on the MainForm to show our new records.  
    ClearTextBox(Me)
    RefreshDGV()
    Me.Close()
End Sub

我怎样才能告诉textbox5哪个是ID字段,成为访问数据库中的下一个数字?

2 个答案:

答案 0 :(得分:0)

打开Access数据库,显示表的结构,并将ID字段类型从数字更改为AutoNumber

现在您的代码不需要将任何内容传递给Access,因为该号码将自动从Access处理。

您可以将这些行添加到代码中,以获取Access对您的字段分配的数字

Dim sqlinsert As String
sqlinsert = "INSERT INTO Table1(Title, YearofFilm, Description, Field1)" & _
            "VALUES(@Title, @YearofFilm, @Description, @Field1)"
Dim cmd As New OleDbCommand(sqlinsert, con1)
cmd.Parameters.Add(New OleDbParameter("@Title", TextBox1.Text))
cmd.Parameters.Add(New OleDbParameter("@YearofFilm", Convert.ToInt32(TextBox2.Text)))
cmd.Parameters.Add(New OleDbParameter("@Description", TextBox3.Text))
cmd.Parameters.Add(New OleDbParameter("@Field1", TextBox4.Text))
con1.Open()
cmd.ExecuteNonQuery()
cmd.Parameters.Clear()
cmd.CommandText = "SELECT @@IDENTITY"
Dim assignedID = Convert.ToInt32(cmd.ExecuteScalar())
' Eventually
TextBox5.Text = assignedID.ToString
con1.Close()
......

另见 How to retrieve last autoincremented value in MS-Access like @@Identity in Sql Server

答案 1 :(得分:0)

创建一个SELECT语句以从表中检索最大数字并向其中添加一个。我不知道VB.Net,所以它应该是类似的东西。

maxQry = "SELECT Max(IDColumnName) As MaxID FROM theTableName;"
Dim cmd As New OleDbCommand(maxQry, con1)
dr = cmd.ExecuteReader
If dr.HasRows Then
    While dr.Read()
        TextBox5.Text = dr("MaxID").ToString
    End While
End If

除非该字段是自动编号类型,否则您根本不必担心它。