vb向access数据库添加记录的问题 用data控件 怎样点击command1使text中的内容添加进数据库生成新的表
1个回答
展开全部
先定义新的连接数据库的oledb对象先
Dim oleCn As New OleDbConnection
Dim oleCd As New OleDbCommand
Dim oleDr As OleDbDataReader
Dim oleAd As New OleDbDataAdapter
Dim ds As New DataSet
Public Event myEvent(ByVal s As String)
然后创建构造函数进行数据库连接
Public Sub New(ByVal databasename As String)
MyBase.new()
Try
oleCn.ConnectionString = "provider=microsoft.jet.oledb.4.0;data source=" & databasename
oleCd.Connection = oleCn
oleAd.SelectCommand = oleCd
ds.Tables.Add("t")
Catch ex As Exception
RaiseEvent ErrorEvent(Me, ex.Message)
End Try
End Sub
然后就能把text中的数据添加到数据库中
Private Sub Command1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Command1.Click
Dim sql As String
sql = "insert into " & tblName & "(字段名1,字段名2,字段名3 , ....) Values('" _
& text1 & "','" & text2& "','" & text3 ......& "')"
Try
oleCd.CommandText = sql
oleCd.Connection.Open()
oleCd.ExecuteReader()
oleCd.Connection.Close()
RaiseEvent myEvent("add success")
Catch ex As Exception
msgbox( ex.Message)
End Try
End Sub
Dim oleCn As New OleDbConnection
Dim oleCd As New OleDbCommand
Dim oleDr As OleDbDataReader
Dim oleAd As New OleDbDataAdapter
Dim ds As New DataSet
Public Event myEvent(ByVal s As String)
然后创建构造函数进行数据库连接
Public Sub New(ByVal databasename As String)
MyBase.new()
Try
oleCn.ConnectionString = "provider=microsoft.jet.oledb.4.0;data source=" & databasename
oleCd.Connection = oleCn
oleAd.SelectCommand = oleCd
ds.Tables.Add("t")
Catch ex As Exception
RaiseEvent ErrorEvent(Me, ex.Message)
End Try
End Sub
然后就能把text中的数据添加到数据库中
Private Sub Command1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Command1.Click
Dim sql As String
sql = "insert into " & tblName & "(字段名1,字段名2,字段名3 , ....) Values('" _
& text1 & "','" & text2& "','" & text3 ......& "')"
Try
oleCd.CommandText = sql
oleCd.Connection.Open()
oleCd.ExecuteReader()
oleCd.Connection.Close()
RaiseEvent myEvent("add success")
Catch ex As Exception
msgbox( ex.Message)
End Try
End Sub
追问
我菜鸟啊555您老写这么长 我看不懂 简单点好不 最好是傻瓜式的! 分类没搞好....忘了 晕死!
追答
不会吧!!!!汗, 里面就只有一个Text属性为Command的button控件,一个构造函数,和一个自定义事件而已喔! I 服了 You
这几句肯定要有
Dim oleCn As New OleDbConnection
Dim oleCd As New OleDbCommand
Dim oleDr As OleDbDataReader
Dim oleAd As New OleDbDataAdapter
Dim ds As New DataSet
然后就能把textBox中的数据添加到数据库中
Private Sub Command1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Command1.Click
oleCn.ConnectionString = "provider=microsoft.jet.oledb.4.0;data source=" & databasename
oleCd.Connection = oleCn
oleAd.SelectCommand = oleCd
ds.Tables.Add("t")
Dim sql As String
sql = "insert into " & tblName & "(字段名1,字段名2,字段名3 , ....) Values('" _
& TextBox1 & "','" & TextBox2& "','" & TextBox3 ......& "')"
oleCd.CommandText = sql
oleCd.Connection.Open()
oleCd.ExecuteReader()
oleCd.Connection.Close()
End Sub
这样是最最最简单的了,可不能再晕了阿!
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询