这位同志信誉很好,支持!修改系统的短日期格式 Public Const LOCALE_SSHORTDATE As Long = &H1F Public Const LOCALE_USER_DEFAULT As Long = &H400Public Declare Function GetLocaleInfo Lib "kernel32" Alias "GetLocaleInfoA" (ByVal lLocale As Long, ByVal lLocaleType As Long, ByVal sLCData As String, ByVal lBufferLength As Long) As Long Public Declare Function SetLocaleInfo Lib "kernel32" Alias "SetLocaleInfoA" (ByVal Locale As Long, ByVal LCType As Long, ByVal lpLCData As String) As LongPublic Function mdlChangeSystemDateFormat(strFormat As String) As Boolean Dim strShortDateFormat As String, strBuffer As String Dim lBuffSize As Long, lRetVal As Long
'Get current short date format lRetVal = GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_SSHORTDATE, strBuffer, lBuffSize)
If lRetVal > 0 Then strShortDateFormat = Left(strBuffer, lRetVal - 1) Else Exit Function End If
'If current short date format is different from your format, change it. 'Note: MMM should be used in capital for month,small m are for minutes If UCase(strShortDateFormat) <> UCase(strFormat) Then lRetVal = SetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_SSHORTDATE, strFormat) End If
If lRetVal > 0 Then mdlChangeSystemDateFormat = True End Function
'****************************读文件成二进制数据,然后存到数据库中************************ Public Sub WriteBinary(ByRef Fld As ADODB.Field, DiskFile As String) Dim NumBlocks As Long '′定义数据块个数 Dim FileLength As Long '′标识文件长度 Dim LeftOver As Long ''定义剩余字节长度 Dim SourceFile As Long '′定义自由文件号 Dim i As Long '′定义循环变量
SourceFile = FreeFile '′提供一个尚未使用的文件号
Open DiskFile For Binary Access Read As SourceFile '′打开文件 FileLength = LOF(SourceFile) '′得到文件长度 'MsgBox FileLength If FileLength = 0 Then '′判断文件是否存在 Close SourceFile MsgBox DiskFile & " 无 内 容 或 不 存 在 !" Else Fld.value = Null ReDim ByteData(FileLength - 1) Get SourceFile, , ByteData() '′读到内存块中 Fld.AppendChunk ByteData() '′写入字段 Close SourceFile '′关闭源文件 End If End Sub
'调用如下ExporToExcel("select * from table")则实现将其导出到EXCEL中Public Function ExporToExcel(strOpen As String) '********************************************************* '* 名称:ExporToExcel '* 功能:导出数据到EXCEL '* 用法:ExporToExcel(sql查询字符串) '********************************************************* Dim Rs_Data As New ADODB.Recordset Dim Irowcount As Integer Dim Icolcount As Integer
Dim xlApp As New Excel.Application Dim xlBook As Excel.Workbook Dim xlSheet As Excel.Worksheet Dim xlQuery As Excel.QueryTable
With Rs_Data If .State = adStateOpen Then .Close End If .ActiveConnection = Cn .CursorLocation = adUseClient .CursorType = adOpenStatic .LockType = adLockReadOnly .Source = strOpen .Open End With With Rs_Data If .RecordCount < 1 Then MsgBox ("没有记录!") Exit Function End If '记录总数 Irowcount = .RecordCount '字段总数 Icolcount = .Fields.Count End With
Set xlApp = CreateObject("Excel.Application") Set xlBook = Nothing Set xlSheet = Nothing Set xlBook = xlApp.Workbooks().Add Set xlSheet = xlBook.Worksheets("sheet1") xlApp.Visible = True
'添加查询语句,导入EXCEL数据 Set xlQuery = xlSheet.QueryTables.Add(Rs_Data, xlSheet.Range("a1"))
xlApp.Application.Visible = True Set xlApp = Nothing '"交还控制给Excel Set xlBook = Nothing Set xlSheet = NothingEnd Function
'********************************************************* '* 名称:BackupDatabase '* 功能:备份数据库 '* 控件:一个文本框和两个按钮(备份到和确定) '********************************************************* Public Sub BackupDatabase() Dim cn As New ADODB.Connection Dim s_path, s_dataexport As String s_path = App.Path Me.MousePointer = 11 '设置鼠标指针形状 'student1是需要备份的数据库名称 s_dataexport = "backup database student1 to disk='" + CommonDialog1.FileName + "'" cn.Open "driver={sql server};server=" & d1 & ";database=student1;persist security info=false; userid=sa" '数据库连接字符串 '这里不需要连接master数据库,即可完成备份 cn.BeginTrans cn.Execute s_dataexport Err.Number = 0 If Err.Number = 0 Then cn.CommitTrans MsgBox "数据备份成功!", vbInformation, "提示" MsgBox "数据备份文件存放路径:" & CommonDialog1.FileName, vbOKOnly, "提示" Unload Me Else cn.RollbackTrans MsgBox "数据备份失败!请检查数据库是否正在打开!", vbCritical, "提示" End If cn.Close Set cn = Nothing Me.MousePointer = 1 End Sub'********************************************************* '* 名称:RestoreDataBase '* 功能:还原数据库 '* 控件:一个文本框和两个按钮( 打开和确定) '********************************************************* Public Sub RestoreDataBase() If Text1.Text = "" Then MsgBox "请选择要恢复的数据文件!", vbInformation, "提示" Exit Sub Else ret = MsgBox("数据恢复操作将会覆盖以前的所有数据并且覆盖后无法恢复,您确定要进行恢复操作吗?", vbQuestion + vbOKCancel, "提示") If ret = vbOK Then Dim cn As New ADODB.Connection Dim sn As New ADODB.Recordset Dim s_restore As String Me.MousePointer = 11 cn.Open "Provider=SQLOLEDB.1;Persist Security Info=False;server=" & d1 & ";Initial Catalog=master;Data Source=127.0.0.1;user id=sa;password=" & d3 & "" sn.Open "select spid from sysprocesses where dbid=db_id('student1')", cn Do While Not sn.EOF cn.Execute "kill " & sn("spid") sn.MoveNext Loop sn.Close s_restore = "restore database student1 from disk='" + Trim(Text1.Text) + "' with REPLACE" cn.Execute s_restore 'Debug.Print gs_conn_string '此时需要连接master数据库才能完成数据恢复操作 '同上student1为需要恢复的数据库 s_restore = "restore database student1 from disk='" + Trim(Text1.Text) + "'" 'text1一个用于记录需要恢复文件的地址的textbox cn.Execute s_restore cn.BeginTrans If Err.Number = 0 Then cn.CommitTrans MsgBox "数据恢复成功!", vbInformation, "提示" Command1.Enabled = True Label1.Visible = False Else cn.RollbackTrans MsgBox "数据恢复失败!", vbCritical, "提示" Command1.Enabled = True End If cn.Close Set cn = Nothing Me.MousePointer = 1 Else Exit Sub End If On Error Resume Next Dim DBC As New DataBaseConnection If db.State = 1 Then db.Close End If db.ConnectionString = DBC.SqlConnectString(d1, d2, d3) rs.CursorType = adOpenDynamic rs.CursorLocation = adUseClient rs.LockType = adLockOptimistic db.CursorLocation = adUseClient db.Open Set cmd.ActiveConnection = db If Err.Number Then MsgBox Err.Description, 16 + vbOKOnly, Err.Number Exit Sub End If db.DefaultDatabase = "student1" If Err.Number Then MsgBox Err.Description, 16 + vbOKOnly, Err.Number Exit Sub End If End If End Sub
得到所有的表名,字段名放入ComboBox 1 select name from msysobjects where type=12 Function GetTables(cnn As ADODB.Connection) As Boolean 'Purpose : Get table names from the Connection given 'Input : cnn, ther ADODB.Connection 'Output : TRUE/FALSE ' On Error GoTo GetTables_ErrorHandler Dim rstSchema As ADODB.Recordset cboTablesName.Clear
Set rstSchema = cnn.OpenSchema(adSchemaTables, Array(Empty, Empty, Empty, "Table")) Do Until rstSchema.EOF If StrComp(Left(rstSchema!TABLE_NAME, 4), "MSys", vbTextCompare) <> 0 Then cboTablesName.AddItem rstSchema!TABLE_NAME End If rstSchema.MoveNext Loop
rstSchema.Close Set rstSchema = Nothing
ErrorHandler: Exit Function GetTables_ErrorHandler: Screen.MousePointer = 0 MsgBox Err.Description Resume ErrorHandler End Function3 Function GetFields(strTableName As String, cnn As ADODB.Connection) As Boolean 'Purpose : Get field names from the table selected and Connection given 'Input : strTableName - the table name; cnn - ther ADODB.Connection 'Output : TRUE/FALSE ' On Error GoTo GetFields_ErrorHandler Screen.MousePointer = 11 Dim adoFields As ADODB.Fields Dim rstTable As ADODB.Recordset Dim strSQL As String
cboFieldsName.Clear
strSQL = "SELECT TOP 1 * FROM [" & strTableName & "] " Set rstTable = New ADODB.Recordset
rstTable.Open strSQL, cnn, adOpenStatic, adLockPessimistic, adCmdText Dim fld As ADODB.Field
For Each fld In rstTable.Fields cboFieldsName.AddItem fld.Name Next
rstTable.Close Set rstTable = Nothing
Screen.MousePointer = 0
ErrorHandler: Exit Function GetFields_ErrorHandler: Screen.MousePointer = 0 MsgBox Err.Description Resume ErrorHandlerEnd Function
Public Const LOCALE_SSHORTDATE As Long = &H1F
Public Const LOCALE_USER_DEFAULT As Long = &H400Public Declare Function GetLocaleInfo Lib "kernel32" Alias "GetLocaleInfoA" (ByVal lLocale As Long, ByVal lLocaleType As Long, ByVal sLCData As String, ByVal lBufferLength As Long) As Long
Public Declare Function SetLocaleInfo Lib "kernel32" Alias "SetLocaleInfoA" (ByVal Locale As Long, ByVal LCType As Long, ByVal lpLCData As String) As LongPublic Function mdlChangeSystemDateFormat(strFormat As String) As Boolean Dim strShortDateFormat As String, strBuffer As String
Dim lBuffSize As Long, lRetVal As Long
lBuffSize = 256
strBuffer = String(lBuffSize, vbNullChar)
'Get current short date format
lRetVal = GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_SSHORTDATE, strBuffer, lBuffSize)
If lRetVal > 0 Then
strShortDateFormat = Left(strBuffer, lRetVal - 1)
Else
Exit Function
End If
'If current short date format is different from your format, change it.
'Note: MMM should be used in capital for month,small m are for minutes
If UCase(strShortDateFormat) <> UCase(strFormat) Then
lRetVal = SetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_SSHORTDATE, strFormat)
End If
If lRetVal > 0 Then mdlChangeSystemDateFormat = True
End Function
Public Sub WriteBinary(ByRef Fld As ADODB.Field, DiskFile As String)
Dim NumBlocks As Long '′定义数据块个数
Dim FileLength As Long '′标识文件长度
Dim LeftOver As Long ''定义剩余字节长度
Dim SourceFile As Long '′定义自由文件号
Dim i As Long '′定义循环变量
SourceFile = FreeFile '′提供一个尚未使用的文件号
Open DiskFile For Binary Access Read As SourceFile
'′打开文件
FileLength = LOF(SourceFile) '′得到文件长度
'MsgBox FileLength
If FileLength = 0 Then '′判断文件是否存在
Close SourceFile
MsgBox DiskFile & " 无 内 容 或 不 存 在 !"
Else
Fld.value = Null
ReDim ByteData(FileLength - 1) Get SourceFile, , ByteData() '′读到内存块中
Fld.AppendChunk ByteData() '′写入字段
Close SourceFile '′关闭源文件
End If
End Sub
'*********************************************************
'* 名称:ExporToExcel
'* 功能:导出数据到EXCEL
'* 用法:ExporToExcel(sql查询字符串)
'*********************************************************
Dim Rs_Data As New ADODB.Recordset
Dim Irowcount As Integer
Dim Icolcount As Integer
Dim xlApp As New Excel.Application
Dim xlBook As Excel.Workbook
Dim xlSheet As Excel.Worksheet
Dim xlQuery As Excel.QueryTable
With Rs_Data
If .State = adStateOpen Then
.Close
End If
.ActiveConnection = Cn
.CursorLocation = adUseClient
.CursorType = adOpenStatic
.LockType = adLockReadOnly
.Source = strOpen
.Open
End With
With Rs_Data
If .RecordCount < 1 Then
MsgBox ("没有记录!")
Exit Function
End If
'记录总数
Irowcount = .RecordCount
'字段总数
Icolcount = .Fields.Count
End With
Set xlApp = CreateObject("Excel.Application")
Set xlBook = Nothing
Set xlSheet = Nothing
Set xlBook = xlApp.Workbooks().Add
Set xlSheet = xlBook.Worksheets("sheet1")
xlApp.Visible = True
'添加查询语句,导入EXCEL数据
Set xlQuery = xlSheet.QueryTables.Add(Rs_Data, xlSheet.Range("a1"))
With xlQuery
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = True
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.PreserveColumnInfo = True
End With
xlQuery.FieldNames = True '显示字段名
xlQuery.Refresh
With xlSheet
.Range(.Cells(1, 1), .Cells(1, Icolcount)).Font.Name = "黑体"
'设标题为黑体字
.Range(.Cells(1, 1), .Cells(1, Icolcount)).Font.Bold = True
'标题字体加粗
.Range(.Cells(1, 1), .Cells(Irowcount + 1, Icolcount)).Borders.LineStyle = xlContinuous
'设表格边框样式
End With
With xlSheet.PageSetup
.LeftHeader = "" & Chr(10) & "&""楷体_GB2312,常规""&10公司名称:" ' & Gsmc
.CenterHeader = "&""楷体_GB2312,常规""公司人员情况表&""宋体,常规""" & Chr(10) & "&""楷体_GB2312,常规""&10日 期:"
.RightHeader = "" & Chr(10) & "&""楷体_GB2312,常规""&10单位:"
.LeftFooter = "&""楷体_GB2312,常规""&10制表人:"
.CenterFooter = "&""楷体_GB2312,常规""&10制表日期:"
.RightFooter = "&""楷体_GB2312,常规""&10第&P页 共&N页"
End With
xlApp.Application.Visible = True
Set xlApp = Nothing '"交还控制给Excel
Set xlBook = Nothing
Set xlSheet = NothingEnd Function
'* 名称:BackupDatabase
'* 功能:备份数据库
'* 控件:一个文本框和两个按钮(备份到和确定)
'*********************************************************
Public Sub BackupDatabase()
Dim cn As New ADODB.Connection
Dim s_path, s_dataexport As String
s_path = App.Path
Me.MousePointer = 11 '设置鼠标指针形状
'student1是需要备份的数据库名称
s_dataexport = "backup database student1 to disk='" + CommonDialog1.FileName + "'"
cn.Open "driver={sql server};server=" & d1 & ";database=student1;persist security info=false; userid=sa" '数据库连接字符串
'这里不需要连接master数据库,即可完成备份
cn.BeginTrans
cn.Execute s_dataexport
Err.Number = 0
If Err.Number = 0 Then
cn.CommitTrans
MsgBox "数据备份成功!", vbInformation, "提示"
MsgBox "数据备份文件存放路径:" & CommonDialog1.FileName, vbOKOnly, "提示"
Unload Me
Else
cn.RollbackTrans
MsgBox "数据备份失败!请检查数据库是否正在打开!", vbCritical, "提示"
End If
cn.Close
Set cn = Nothing
Me.MousePointer = 1
End Sub'*********************************************************
'* 名称:RestoreDataBase
'* 功能:还原数据库
'* 控件:一个文本框和两个按钮( 打开和确定)
'*********************************************************
Public Sub RestoreDataBase()
If Text1.Text = "" Then
MsgBox "请选择要恢复的数据文件!", vbInformation, "提示"
Exit Sub
Else
ret = MsgBox("数据恢复操作将会覆盖以前的所有数据并且覆盖后无法恢复,您确定要进行恢复操作吗?", vbQuestion + vbOKCancel, "提示")
If ret = vbOK Then
Dim cn As New ADODB.Connection
Dim sn As New ADODB.Recordset
Dim s_restore As String
Me.MousePointer = 11
cn.Open "Provider=SQLOLEDB.1;Persist Security Info=False;server=" & d1 & ";Initial Catalog=master;Data Source=127.0.0.1;user id=sa;password=" & d3 & ""
sn.Open "select spid from sysprocesses where dbid=db_id('student1')", cn
Do While Not sn.EOF
cn.Execute "kill " & sn("spid")
sn.MoveNext
Loop
sn.Close
s_restore = "restore database student1 from disk='" + Trim(Text1.Text) + "' with REPLACE"
cn.Execute s_restore
'Debug.Print gs_conn_string
'此时需要连接master数据库才能完成数据恢复操作
'同上student1为需要恢复的数据库
s_restore = "restore database student1 from disk='" + Trim(Text1.Text) + "'"
'text1一个用于记录需要恢复文件的地址的textbox
cn.Execute s_restore
cn.BeginTrans
If Err.Number = 0 Then
cn.CommitTrans
MsgBox "数据恢复成功!", vbInformation, "提示"
Command1.Enabled = True
Label1.Visible = False
Else
cn.RollbackTrans
MsgBox "数据恢复失败!", vbCritical, "提示"
Command1.Enabled = True
End If
cn.Close
Set cn = Nothing
Me.MousePointer = 1
Else
Exit Sub
End If
On Error Resume Next
Dim DBC As New DataBaseConnection
If db.State = 1 Then
db.Close
End If
db.ConnectionString = DBC.SqlConnectString(d1, d2, d3)
rs.CursorType = adOpenDynamic
rs.CursorLocation = adUseClient
rs.LockType = adLockOptimistic
db.CursorLocation = adUseClient
db.Open
Set cmd.ActiveConnection = db
If Err.Number Then
MsgBox Err.Description, 16 + vbOKOnly, Err.Number
Exit Sub
End If
db.DefaultDatabase = "student1"
If Err.Number Then
MsgBox Err.Description, 16 + vbOKOnly, Err.Number
Exit Sub
End If
End If
End Sub
1
select name from msysobjects where type=12
Function GetTables(cnn As ADODB.Connection) As Boolean
'Purpose : Get table names from the Connection given
'Input : cnn, ther ADODB.Connection
'Output : TRUE/FALSE
'
On Error GoTo GetTables_ErrorHandler
Dim rstSchema As ADODB.Recordset
cboTablesName.Clear
Set rstSchema = cnn.OpenSchema(adSchemaTables, Array(Empty, Empty, Empty, "Table"))
Do Until rstSchema.EOF
If StrComp(Left(rstSchema!TABLE_NAME, 4), "MSys", vbTextCompare) <> 0 Then
cboTablesName.AddItem rstSchema!TABLE_NAME
End If
rstSchema.MoveNext
Loop
rstSchema.Close
Set rstSchema = Nothing
ErrorHandler:
Exit Function
GetTables_ErrorHandler:
Screen.MousePointer = 0
MsgBox Err.Description
Resume ErrorHandler
End Function3
Function GetFields(strTableName As String, cnn As ADODB.Connection) As Boolean
'Purpose : Get field names from the table selected and Connection given
'Input : strTableName - the table name; cnn - ther ADODB.Connection
'Output : TRUE/FALSE
'
On Error GoTo GetFields_ErrorHandler
Screen.MousePointer = 11 Dim adoFields As ADODB.Fields
Dim rstTable As ADODB.Recordset
Dim strSQL As String
cboFieldsName.Clear
strSQL = "SELECT TOP 1 * FROM [" & strTableName & "] " Set rstTable = New ADODB.Recordset
rstTable.Open strSQL, cnn, adOpenStatic, adLockPessimistic, adCmdText
Dim fld As ADODB.Field
For Each fld In rstTable.Fields
cboFieldsName.AddItem fld.Name
Next
rstTable.Close
Set rstTable = Nothing
Screen.MousePointer = 0
ErrorHandler:
Exit Function
GetFields_ErrorHandler:
Screen.MousePointer = 0
MsgBox Err.Description
Resume ErrorHandlerEnd Function