我想知道如何在C#中使用Windows DataGridView DataTable创建新的Microsoft Access Table。
请帮我解决这个问题。 我试过创建空表。但是我的大多数数据库语句都是硬编码的。 (例如,我将所有列设为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;
}
答案 0 :(得分:0)
This post专门显示代码
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