2014-01-15 123 views
0

我創建了下面的代碼在不同的Form插入一個Access數據庫新行

窗體2

private DataTable dataTable; 

internal void ReadTable(ref DataTable dt) 
{ 
    dataTable = dt; 
} 

private void button1_Click(object sender, EventArgs e) 
{ 
    DataRow dataRow = dataTable.NewRow(); 
    foreach (ListViewItem item in listView1.Items) 
    { 
     dataRow[item.SubItems[1].Text] = item.SubItems[item.SubItems.Count - 1].Text; 
    } 
    dataTable.Rows.Add(dataRow); 
} 

Form1中

private void button1_Click(object sender, EventArgs e) 
{ 
    using (Form2 form = new Form2()) 
    { 
     form.ReadTable(ref dataTable); 
     form.ShowDialog(); 

     using (OleDbConnection oledbConnection = new OleDbConnection(connection)) 
     { 
     oledbConnection.Open(); 
     string query = "SELECT * FROM Student"; 
     using (OleDbCommand oledbCommand = new OleDbCommand(query, oledbConnection)) 
     { 
      using (OleDbDataAdapter oledbDataAdapter = new OleDbDataAdapter(oledbCommand)) 
      { 
       using (OleDbCommandBuilder oledbCommandBuilder = new OleDbCommandBuilder(oledbDataAdapter)) 
       { 
        oledbDataAdapter.DeleteCommand = oledbCommandBuilder.GetDeleteCommand(true); 
        oledbDataAdapter.InsertCommand = oledbCommandBuilder.GetInsertCommand(true); 
        oledbDataAdapter.UpdateCommand = oledbCommandBuilder.GetUpdateCommand(true); 
        oledbDataAdapter.Update(dataTable); 
       } 
      } 
      } 
      oledbConnection.Close(); 
     } 
    } 
} 

爲什麼讓我在INSERT語法錯誤INTO聲明?

+0

任何具體情況如何? –

+0

不,它只是告訴我,有一個語法錯誤:(我試圖看到INSERT INTO命令的代碼,並證明是正確的 – user3105160

+0

你可以編輯你的問題,並粘貼結果插入命令的SQL? –

回答

2

的解決方案是:在語法錯誤

... 
using (OleDbCommandBuilder oledbCommandBuilder = new OleDbCommandBuilder(oledbDataAdapter)) 
{ 
    oledbCommandBuilder.QuotePrefix = "["; 
    oledbCommandBuilder.QuoteSuffix = "]"; 
    oledbDataAdapter.DeleteCommand = oledbCommandBuilder.GetDeleteCommand(true); 
    oledbDataAdapter.InsertCommand = oledbCommandBuilder.GetInsertCommand(true); 
    oledbDataAdapter.UpdateCommand = oledbCommandBuilder.GetUpdateCommand(true); 
    oledbDataAdapter.Update(dataTable); 
} 
...