vb怎么连接数据库写入数据?

如题所述

'在使用前需要先安装MySql的驱动,进行正确配置
'注意:必须给出正确的服务器名、数据库名、表名、数据库连接的用户名、密码
Option Explicit
Dim Cnn As ADODB.Connection '定义ADO连接对象
Dim Records As ADODB.Recordset '定义ADO记录集对象
'连接到数据库
Function CnnOpen(ByVal ServerName As String, ByVal DBName As String, ByVal TblName As String, ByVal User As String, ByVal PWD As String) '服务器名或IP、数据库名、登录用户、密码
Dim CnnStr As String '定义连接字符串
Set Cnn = CreateObject("ADODB.Connection") '创建ADO连接对象
Cnn.CommandTimeout = 15 '设置超时时间
CnnStr = "DRIVER={MySql ODBC 5.1 Driver};SERVER=" & ServerName & ";Database=" & DBName & ";Uid=" & User & ";Pwd=" & PWD & ";Stmt=set names GBK" '
Cnn.ConnectionString = CnnStr
Cnn.Open
End Function
'关闭连接
Function CnnClose()
If Cnn.State = 1 Then
Cnn.Close
End If
End Function
'把Excel写入MySql中的数据库
Function InsertToMySql(ByVal SheetName As String, ByVal TblName As String)
Dim SqlStr As String
Dim i, j As Integer
Dim Columns, Rows As Integer
Columns = VBAProject.func_public.GetTotalColumns(SheetName)
Rows = VBAProject.func_public.GetTotalRows(SheetName)
Set Records = CreateObject("ADODB.recordset")
'取得结果集并插入数据到数据库
Set Records = CreateObject("ADODB.Recordset")
'以下语句提供了插入思路,我只是把单条记录的插入方式改为循环,以把所有的记录添加到表中
'rs.Open "insert into newtable values('" & ActiveSheet.Cells(i, 1).Value & "'," & "'" & ActiveSheet.Cells(i, 2).Value & "')", cnn, 0
For i = 2 To Rows
SqlStr = "INSERT INTO " & TblName & " values('" & Sheets(SheetName).Cells(i, 1).Value & "'" '注意:" values('",字母“v”之前是有空格的!!!
For j = 2 To Columns
SqlStr = SqlStr & ",'" & Sheets(SheetName).Cells(i, j).Value & "'"
Next
SqlStr = SqlStr & ")"
Set Records = Cnn.Execute(SqlStr) 'rs.Open SqlStr, cnn, 0 不能用这条语句实现!!!
Next
MsgBox "Insert!", vbOKOnly, "Excel To MySql"
End Function
'清除对象
Function ClearObj()
Set Cnn = Nothing
Set Records = Nothing
End Function
温馨提示:内容为网友见解,仅供参考
第1个回答  推荐于2016-02-21
Option Explicit
Dim Hwd As Long '存放窗体句柄
Dim pid As Long '存放进程ID
Dim hProcess As Long '存放进程句柄
Dim H As Long '存放二级指针
Dim buffer As Long '存放一级指针
Dim HP As Integer '存放血量
Dim MP As Integer '存放魔法值
Dim JY As Integer '存放经验值
Dim MaxMp As Integer '存放魔法上限
Dim MaxHp As Integer '存放血量上限
Dim DJ As Integer '人物等级
Private Sub Form_Load()
Hwd = FindWindow(vbNullString, "Element Client") '读取HWND
If Hwd = 0 Then
MsgBox "游戏未运行!!!!!", , "游戏未运行"
End If
GetWindowThreadProcessId Hwd, pid '获取进程标识符
hProcess = OpenProcess(PROCESS_ALL_ACCESS, 0, pid) '将进程标识符做为参数,返回目标进程PID的句柄,得到此句柄后即可对目标进行读写操,PROCESS_ALL_ACCESS表示完全控制,权限最大
If hProcess = 0 Then
MsgBox "不能打开进程!!!!!", , "打开进程错误"
Exit Sub
End If本回答被提问者采纳
第2个回答  2015-11-17
相似回答