如何使用 vb.net 添加缺失的列并忽略 ms access dbase 中的现有列?
How to add missing columns and ignoring existing columns in ms access dbase with vb.net?
场景是这样的。我有一个现有的 MS 访问数据库。数据库里面有Table1。假设我不知道那里已经有哪些列或现有列。我的程序使用 vb.net 形式,只需单击一个按钮,我就可以添加所有列,如姓名、薪水、地址、日期记录和更新。添加所有这些列没有问题,因为它们不存在于 Table1 中。我的问题是在一些数据库 Table1 中,一些 columns/fields 已经存在,比如工资和地址,我想添加列名称、daterec 和更新但它给了我一个错误 "Field 'name' 已经存在于 Table 'Table1' 中。
我应该怎么办?我只想添加 Table1 中尚不存在的那些列。我想忽略那些现有的列并继续添加那些缺失的列。非常感谢任何建议。
下面是添加列和修改的代码。谢谢。
Dim ConnString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|addcolumn.accdb"
Dim SqlString As String = "ALTER TABLE Table1 ADD COLUMN " + "name Text(250)," + "salary Number," + "address Memo," + "daterec DateTime," + "updated YesNo" 'Datatypes: Text is ShortText, Number is Number(Double), Memo is LongText, DateTime is Date or/and Time, YesNo is either checkbox/True or False/On or Off depends in saving format .
Using conn As New OleDbConnection(ConnString)
Using cmd As New OleDbCommand(SqlString, conn)
conn.Open()
cmd.ExecuteNonQuery()
End Using
End Using
这里的挑战是您注意到的吗?
有些字段可能存在,有些可能不存在。
所以,你必须逐个字段测试+添加
像这样的东西应该可以工作:
Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
Dim strCon As String
strCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Test\test44.accdb"
Using dbCon As New OleDbConnection(strCon)
dbCon.Open()
AddFieldExist("table1", "name", "Text(250)", dbCon)
AddFieldExist("table1", "Salary", "number", dbCon)
AddFieldExist("table1", "Address", "memo", dbCon)
AddFieldExist("table1", "Address", "memo", dbCon)
AddFieldExist("table1", "DateRec", "datetime", dbCon)
AddFieldExist("table1", "Upated", "YesNo", dbCon)
End Using
End Sub
Sub AddFieldExist(strTable As String,
strField As String,
strType As String,
dbCon As OleDb.OleDbConnection)
' return true/false if field exist.
Dim tblDef As New DataTable
Dim oReader As New OleDbDataAdapter("SELECT TOP 1 * FROM " & strTable, dbCon)
oReader.Fill(tblDef)
If tblDef.Columns.IndexOf(strField) = -1 Then
' add field
Dim strSQL As String = "ALTER TABLE " & strTable & " ADD COLUMN " & strField & " " & strType
Dim cmd As New OleDbCommand(strSQL, dbCon)
cmd.ExecuteNonQuery()
End If
End Sub
代码确实假定所讨论的 table 确实有数据。如果没有,那么您可能需要在此处引入 getSchema,但就目前而言,以上是我的建议。
我不打算提供答案,因为我认为这个问题没有显示出足够的努力,但是,由于公认的答案不是我认为可取的,我觉得我需要这样做。这段代码按照我在这里和其他地方的相同问题所建议的进行,并且应该按原样工作,尽管我只测试了不同的文件,table 和列名。
Dim tableName = "Table1"
Using connection As New OleDbConnection($"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\addcolumn.accdb")
connection.Open()
'Get a DataTable containing information about all columns in the specified table.
Dim schemaTable = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Columns,
{Nothing, Nothing, tableName})
'Create a list of all new column names and data types to add.
Dim dataTypesByColumnName As New Dictionary(Of String, String) From {{"name", "Text(250)"},
{"salary", "Number"},
{"address", "Memo"},
{"daterec", "DateTime"},
{"updated", "YesNo"}}
'Get a list of the column names already in the table.
Dim existingColumnNames = schemaTable.AsEnumerable().
Select(Function(row) row.Field(Of String)("COLUMN_NAME")).
ToArray()
'Create a list of column definition snippets to insert into SQL code, e.g. "columnName DataType".
Dim columnSnippets = dataTypesByColumnName.Keys.Except(existingColumnNames).
Select(Function(key) String.Format("{0} {1}", key, dataTypesByColumnName(key))).
ToArray()
If columnSnippets.Any() Then
'Construct the full SQL statement.
Dim sql = String.Format("ALTER TABLE {0} ADD COLUMN {1}", tableName, String.Join(", ", columnSnippets))
Dim command As New OleDbCommand(sql, connection)
'Execute the single SQL statement against the database.
command.ExecuteNonQuery()
End If
End Using
它从数据库中获取现有列的列表,从列表中排除要添加的列,然后使用单个 SQL 语句添加其余列。
场景是这样的。我有一个现有的 MS 访问数据库。数据库里面有Table1。假设我不知道那里已经有哪些列或现有列。我的程序使用 vb.net 形式,只需单击一个按钮,我就可以添加所有列,如姓名、薪水、地址、日期记录和更新。添加所有这些列没有问题,因为它们不存在于 Table1 中。我的问题是在一些数据库 Table1 中,一些 columns/fields 已经存在,比如工资和地址,我想添加列名称、daterec 和更新但它给了我一个错误 "Field 'name' 已经存在于 Table 'Table1' 中。 我应该怎么办?我只想添加 Table1 中尚不存在的那些列。我想忽略那些现有的列并继续添加那些缺失的列。非常感谢任何建议。
下面是添加列和修改的代码。谢谢。
Dim ConnString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|addcolumn.accdb"
Dim SqlString As String = "ALTER TABLE Table1 ADD COLUMN " + "name Text(250)," + "salary Number," + "address Memo," + "daterec DateTime," + "updated YesNo" 'Datatypes: Text is ShortText, Number is Number(Double), Memo is LongText, DateTime is Date or/and Time, YesNo is either checkbox/True or False/On or Off depends in saving format .
Using conn As New OleDbConnection(ConnString)
Using cmd As New OleDbCommand(SqlString, conn)
conn.Open()
cmd.ExecuteNonQuery()
End Using
End Using
这里的挑战是您注意到的吗? 有些字段可能存在,有些可能不存在。 所以,你必须逐个字段测试+添加
像这样的东西应该可以工作:
Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
Dim strCon As String
strCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Test\test44.accdb"
Using dbCon As New OleDbConnection(strCon)
dbCon.Open()
AddFieldExist("table1", "name", "Text(250)", dbCon)
AddFieldExist("table1", "Salary", "number", dbCon)
AddFieldExist("table1", "Address", "memo", dbCon)
AddFieldExist("table1", "Address", "memo", dbCon)
AddFieldExist("table1", "DateRec", "datetime", dbCon)
AddFieldExist("table1", "Upated", "YesNo", dbCon)
End Using
End Sub
Sub AddFieldExist(strTable As String,
strField As String,
strType As String,
dbCon As OleDb.OleDbConnection)
' return true/false if field exist.
Dim tblDef As New DataTable
Dim oReader As New OleDbDataAdapter("SELECT TOP 1 * FROM " & strTable, dbCon)
oReader.Fill(tblDef)
If tblDef.Columns.IndexOf(strField) = -1 Then
' add field
Dim strSQL As String = "ALTER TABLE " & strTable & " ADD COLUMN " & strField & " " & strType
Dim cmd As New OleDbCommand(strSQL, dbCon)
cmd.ExecuteNonQuery()
End If
End Sub
代码确实假定所讨论的 table 确实有数据。如果没有,那么您可能需要在此处引入 getSchema,但就目前而言,以上是我的建议。
我不打算提供答案,因为我认为这个问题没有显示出足够的努力,但是,由于公认的答案不是我认为可取的,我觉得我需要这样做。这段代码按照我在这里和其他地方的相同问题所建议的进行,并且应该按原样工作,尽管我只测试了不同的文件,table 和列名。
Dim tableName = "Table1"
Using connection As New OleDbConnection($"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\addcolumn.accdb")
connection.Open()
'Get a DataTable containing information about all columns in the specified table.
Dim schemaTable = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Columns,
{Nothing, Nothing, tableName})
'Create a list of all new column names and data types to add.
Dim dataTypesByColumnName As New Dictionary(Of String, String) From {{"name", "Text(250)"},
{"salary", "Number"},
{"address", "Memo"},
{"daterec", "DateTime"},
{"updated", "YesNo"}}
'Get a list of the column names already in the table.
Dim existingColumnNames = schemaTable.AsEnumerable().
Select(Function(row) row.Field(Of String)("COLUMN_NAME")).
ToArray()
'Create a list of column definition snippets to insert into SQL code, e.g. "columnName DataType".
Dim columnSnippets = dataTypesByColumnName.Keys.Except(existingColumnNames).
Select(Function(key) String.Format("{0} {1}", key, dataTypesByColumnName(key))).
ToArray()
If columnSnippets.Any() Then
'Construct the full SQL statement.
Dim sql = String.Format("ALTER TABLE {0} ADD COLUMN {1}", tableName, String.Join(", ", columnSnippets))
Dim command As New OleDbCommand(sql, connection)
'Execute the single SQL statement against the database.
command.ExecuteNonQuery()
End If
End Using
它从数据库中获取现有列的列表,从列表中排除要添加的列,然后使用单个 SQL 语句添加其余列。