【发布时间】:2017-03-04 06:30:03
【问题描述】:
通过创建具有相同表的新 .accdb 并将表从 .mdbs 转换为 .accdbs,并且这些表具有相同的列名和相同的列数据类型。使用 OleDB 和 sql 来执行非查询。当我尝试从旧数据表列中为新列使用相同的数据类型时,我遇到了问题。我带来了填充 dTable
adp.Fill(dTable)
以下代码让我遇到了除 varchar 之外的不同数据类型的列。
Public Sub ConvertTable(dTable As DataTable, tableName As String)
Dim i As Int16 = 0
Dim j As Int16 = 0
strConnOutput = SharedRoutines.GetAccessACEConnectionString(aceDatabase)
Using con2 As New OleDbConnection(strConnOutput)
con2.Open()
Dim sqlText As String = ""
'Set up query to create a table with the same name as the'
'spreadsheet.'
sqlText = "CREATE TABLE [" & tableName & "] ("
'Create all the columns that exist in the spreadsheet.'
For Each col As DataColumn In dTable.Columns
sqlText &= "[" & col.ColumnName & "] varchar, "
Next
'Clean up the end of the CREATE query.'
sqlText = sqlText.Substring(0, sqlText.Length - 2) & ")"
Using cmValid As New OleDbCommand(sqlText, con2)
cmValid.ExecuteNonQuery()
End Using
'Set the INSERT SQL query for the data in the spreadsheet.'
sqlText = "INSERT INTO [" & tableName & "] ("
'Add all the columns to the INSERT query.'
For Each col As DataColumn In dTable.Columns
sqlText &= "[" & col.ColumnName & "], "
Next
'Clean up the end of the query string and prepare for the parameters.'
sqlText = sqlText.Substring(0, sqlText.Length - 2) & ") VALUES ("
'Add all the parameter placeholders to the INSERT query.'
For Each col As DataColumn In dTable.Columns
sqlText &= "?, "
Next
'Clean up the end of the INSERT query.'
sqlText = sqlText.Substring(0, sqlText.Length - 2) & ")"
Try
'Loop through all the rows of data in the spreadsheet.'
For Each rw As DataRow In dTable.Rows
Using cmValid As New OleDbCommand(sqlText, con2)
'Add a parameter for each column.'
For Each col As DataColumn In dTable.Columns
cmValid.Parameters.Add(New OleDbParameter(col.ColumnName, rw(col.ColumnName)))
Next
'Send data to the new table.'
cmValid.ExecuteNonQuery()
End Using
Next
Catch ex As Exception
j += 1
convertResponse &= tableName & " from " & aceDatabase & " was not completed."
MessageBox.Show(tableName & " from " & aceDatabase & " was not completed. Message:" & ex.ToString)
End Try
dTable.Dispose()
i += 1
convertResponse &= "Table " & tableName & " was added to " & aceDatabase & ControlChars.CrLf
End Using
End Sub
我改变了 For Each 循环
For Each col As DataColumn In dTable.Columns
sqlText &= "[" & col.ColumnName & "] " & col.DataType.ToString & ", "
Next
但现在 executeNonQuery() 正在引发语法错误。不是 col.dataType.Tostring 吗? 带有 varchar 的 SqlText CREATE TABLE [BASIC_DESCRIPTION] ([ColumnName] varchar, [Order] varchar) 和....相比 CREATE TABLE [BASIC_DESCRIPTION] ([ColumnName] System.String, [Order] System.Int32) 我的问题是我需要在 sqlText 中添加什么以确保正在创建的新列与旧表的类型相同?我找到的最接近的答案是这个。 Link
【问题讨论】:
-
列名和数据类型完全不一样。您可以/应该从第二个表相关的任何数据库中读取模式;让 NET 构建 DT
-
所以问题不在于 varchar?
-
我不知道,你实际上并没有展示你是如何构建第二张表的。我的水晶球说你只是在一个循环中添加了 DataColumns 而没有指定创建 text/string/varchar 列的类型;因此当列数据是其他内容时出现错误。
-
它将很好地创建表格。我只想确保列的数据类型是相同的。 ExecuteNonQuery() 中的 sqlText 引发错误
-
如果你把错误类型的列放进去,表格就不好了。