VB ado连接数据库,用update无法添加access中数据
DimConnAsNewADODB.ConnectionDimConnstringAsStringDimrs1AsNewADODB.RecordsetPrivateSub...
Dim Conn As New ADODB.Connection
Dim Connstring As String
Dim rs1 As New ADODB.Recordset
Private Sub Command1_Click()
Connstring = "Driver=Microsoft Access Driver (*.mdb);DBQ=" & App.Path & "\..\zhjw.mdb"
With Conn
.ConnectionString = Connstring
.ConnectionTimeout = 10
.Open
End With
MsgBox ("连接成功")
Command1.Enabled = False
Command2.Enabled = True
End Sub
Private Sub Command2_Click()
Command1.Enabled = False
rs1.CursorLocation = adUseClient
rs1.Open "classmanagement", Conn, adOpenDynamic, adLockBatchOptimistic
Set DataGrid1.DataSource = rs1
Command2.Enabled = False
Command3.Enabled = True
End Sub
Private Sub Command3_Click()
Command2.Enabled = False
Command3.Enabled = False
rs1.AddNew
Command4.Enabled = True
End Sub
Private Sub Command4_Click()
If DataGrid1.Columns(0).Text <> "" Then
rs1.Update
Else
MsgBox "不能插入一条空记录或新纪录的主键不能为空"
End If
End Sub
连接成功,表也能显示出来,就是在添加以后access中的表添加不了新纪录。求大神指点! 展开
Dim Connstring As String
Dim rs1 As New ADODB.Recordset
Private Sub Command1_Click()
Connstring = "Driver=Microsoft Access Driver (*.mdb);DBQ=" & App.Path & "\..\zhjw.mdb"
With Conn
.ConnectionString = Connstring
.ConnectionTimeout = 10
.Open
End With
MsgBox ("连接成功")
Command1.Enabled = False
Command2.Enabled = True
End Sub
Private Sub Command2_Click()
Command1.Enabled = False
rs1.CursorLocation = adUseClient
rs1.Open "classmanagement", Conn, adOpenDynamic, adLockBatchOptimistic
Set DataGrid1.DataSource = rs1
Command2.Enabled = False
Command3.Enabled = True
End Sub
Private Sub Command3_Click()
Command2.Enabled = False
Command3.Enabled = False
rs1.AddNew
Command4.Enabled = True
End Sub
Private Sub Command4_Click()
If DataGrid1.Columns(0).Text <> "" Then
rs1.Update
Else
MsgBox "不能插入一条空记录或新纪录的主键不能为空"
End If
End Sub
连接成功,表也能显示出来,就是在添加以后access中的表添加不了新纪录。求大神指点! 展开
3个回答
展开全部
在AddNew后,你要给每个字段赋值,如:
rs1.fields(...)=...
rs1.fields(...)=...
追问
rs1.Fields("classnum") = DataGrid1.Columns(0).Text
这样赋值以后怎么添加不了...........
追答
试了下,要注意如下方面:
1.DataGrid控件的AllowAddnew必须为True,才可以添加记录,如果要删除,还要设置AllowDelete为True,要修改则要设置 AllowUpdate为True
2.在网格里输入记录后,需要执行Update操作,记录才会添加成功,在这里是:rs1.Update。预先执行 rs1.AddNew,会出现一个带三角形箭头的行,在这行输入新记录.
3.不允许添加任何列都无值的空白记录,如连续执行两次rs1.AddNew就会出错。可以在添加rs1.AddNew段加入错误处理,在rs1.Update段也加入错误处理
你这段代码的问题是出在:rs1.Open "classmanagement", Conn, adOpenDynamic, adLockBatchOptimistic,你用adLockBatchOptimistic的锁定模式打开,却用Update去更新,应该使用:rS1.UpdateBatch,或者rs1.Open 改成 rs1.Open "classmanagement", Conn, adOpenDynamic, AdLockOptimistic
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询