从Windows DataGridView DataTable C#创建Microsoft Access表
本文关键字:Microsoft Access 创建 Windows DataGridView DataTable | 更新日期: 2023-09-27 18:26:03
我想知道如何在C#中从Windows DataGridView DataTable创建新的Microsoft Access表。
- 我已经有数据库了。(例如,Database.mdb或.accdb)
- 但我还没有在数据库文件中创建表
- 我已经有了显示表中数据的DataGridView
- 我想创建一个与DataGridView显示的内容完全相同的新表
请帮我解决这个问题。我试过创建空表。但我的大多数数据库语句都是硬编码的。(例如,我将所有列设为VARCHAR数据类型。)我真的很感激。
非常感谢。:)
这些是我的密码。
public void CreateDatabaseTable(string database, string dbTableName)
{
OleDbConnection con;
OleDbCommand cmd;
string queryStr = "";
try
{
con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + database);
con.Open();
queryStr = getDataGridViewHeaders().ToString();
cmd = new OleDbCommand("CREATE TABLE " + dbTableName +
"( [keyID] AUTOINCREMENT PRIMARY KEY NOT NULL," + queryStr + ")", con);
cmd.ExecuteNonQuery();
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
public string getDataGridViewHeaders()
{
int colCount = dataGridView.Columns.Count;
string headerCols = "";
if (colCount > 0)
{
headerCols = "[" + dataGridView.Columns[0].HeaderText + "]" + " VARCHAR";
}
for (int col = 1; col < colCount; col++)
{
headerCols = headerCols + " , " + "[" + dataGridView.Columns[col].HeaderText + "]" + "VARCHAR";
}
Console.WriteLine(headerCols);
return headerCols;
}
这篇文章专门展示了的代码
VB:中的摘录示例
' Part 2: Create one Table using OLEDB Provider
Dim con As New OleDb.OleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source =" & databaseName)
con.Open()
'Get database schema
Dim dbSchema As DataTable = con.GetOleDbSchemaTable(OleDb.OleDbSchemaGuid.Tables, New Object() {Nothing, Nothing, tableName, "TABLE"})
con.Close()
' If the table exists, the count = 1
If dbSchema.Rows.Count > 0 Then
' do whatever you want to do if the table exists
Else
'do whatever you want to do if the table does not exist
' e.g. create a table
Dim cmd As New OleDb.OleDbCommand("CREATE TABLE [" + tableName + "] ([Field1] TEXT(10), [Field2] TEXT(10))", con)
con.Open()
cmd.ExecuteNonQuery()
MessageBox.Show("Table Created Successfully")
con.Close()
End If