Public Shared Function ExportDsToMsAccess(ByVal Name As String, ByVal DT As DataTable, ByVal db As OleDb.OleDbConnection) As Boolean
Dim Sb As New StringBuilder(500)
Sb.Append("Create Table [").Append(Name).Append("] (")
For Each c As DataColumn In DT.Columns
Dim Tc = Type.GetTypeCode(c.DataType)
Sb.Append("[").Append(c.ColumnName).Append("]").Append(" "c)
Select Case Tc
Case TypeCode.String
If c.MaxLength > 255 OrElse c.MaxLength < 0 _
Then Sb.Append("LONGTEXT") _
Else Sb.AppendFormat("Text({0})", c.MaxLength)
Case TypeCode.DateTime : Sb.Append("DateTime")
Case TypeCode.Int16 : Sb.Append("SHORT")
Case TypeCode.Int32 : Sb.Append("INT")
Case TypeCode.Single : Sb.Append("REAL")
Case TypeCode.Double : Sb.Append("FLOAT")
Case TypeCode.Decimal : Sb.Append("NUMBER")
Case TypeCode.Char : Sb.Append("Text(1)")
Case TypeCode.Boolean : Sb.Append("BIT")
Case TypeCode.Byte : Sb.Append("BYTE")
Case Else
If c.DataType Is GetType(Guid) Then
Sb.Append("Text(50)")
Else
Throw New Exception(Tc.ToString & " Tipo no Implementado, Columna: " & c.ColumnName)
End If
End Select
Sb.Append(","c)
Next
Sb.Chars(Sb.Length - 1) = ")"c
Try
Dim cmd As New OleDb.OleDbCommand("Drop Table " & Name, db)
cmd.ExecuteNonQuery()
Catch ex As Exception
End Try
Try
Dim cmd As New OleDb.OleDbCommand(Sb.ToString, db)
cmd.ExecuteNonQuery()
Dim da As New OleDb.OleDbDataAdapter("Select * from " & Name, db)
Dim cb As New OleDb.OleDbCommandBuilder(da)
cmd = cb.GetInsertCommand
Sb.Length = 0
Sb.Append("Insert into [").Append(Name).Append("] Values(")
For n = 1 To DT.Columns.Count : Sb.Append("?,") : Next
Sb.Chars(Sb.Length - 1) = ")"c
cmd.CommandText = Sb.ToString
Dim t As New Stopwatch
t.Start()
For Each r As DataRow In DT.Rows
For n = 0 To DT.Columns.Count - 1
Dim v = r(n)
If TypeOf (v) Is Guid Then v = v.ToString
cmd.Parameters(n).Value = v
Next
cmd.ExecuteNonQuery()
Next
t.Stop()
Debug.Print(t.Elapsed.ToString)
Catch ex As Exception
MessageBox.Show(ex.Message, "Creating Ms Acces Table " & Name)
Debug.Print(Sb.ToString)
Return False
End Try
Return True
End Function
|