2013-09-22 55 views
1

我有一切設置,但現在我只需要添加一個條目到我的表在access.It將是簡單的只顯示我的數據在數據網格視圖和使用綁定有一個具有約束力的導航器的源,但我在這裏是場景:我必須有表格,一個與歌曲名稱,藝術家和流派,另一個表只有流派,這兩個表與流派有關係(與參照完整性)。我想在C#程序中調用一個輸入框來簡單地將新的流派添加到流派表中。既然沒有數據網格視圖或任何其他控件來輕鬆添加條目,那麼向表中添加條目的簡單過程是什麼?在C中使用INSERT sql命令與Access數據庫#

這裏是我的代碼迄今爲適當的事件處理程序:

private void newGenreToolStripMenuItem_Click(object sender, EventArgs e) 
{ 
    //(cnSongs)Connection delacred and instantiated elsewhere 
    cnSongs.Open(); 

    string input = Interaction.InputBox("Genre ", "New Genre", "Type genre here", -1, -1); 

    string InsertSql = "INSERT INTO tblGenres (Genre) VALUES (" + input + ")"; 

    OleDbCommand cmdInsert = new OleDbCommand(InsertSql, cnSongs); 

    //(daSongs)Data Adapter delacred and instantiated elsewhere 
    daSongs = new OleDbDataAdapter(InsertSql, cnSongs); 

    daSongs.InsertCommand = cmdInsert; 

    cmdInsert.ExecuteNonQuery(); 
    cnSongs.Close(); 
} 

我做了大量的研究,只得到了所需要的sql語句,這是有用的,但我需要知道如何exacute它的代碼。

謝謝你的時間。

+0

這看起來是兩回事。首先,帶有'daSongs'的兩行是不相關的(註釋說'daSongs'在其他地方被實例化,顯然它正在被實例化)。其次,你應該學習如何使用'OleDbParameter',因爲你有脆弱的SQL注入。你看到什麼問題?是否有錯誤訊息? – Laurence

+0

對不起,我misspoke,連接和適配器都聲明(但未實例化)全局,但它們只在需要的地方實例化(表單加載事件處理程序中的連接和上述事件處理程序中的適配器)。我沒有遇到錯誤,但是當我運行並且輸入框出現時,我輸入一個值,退出程序並轉到訪問文件,但該值不會添加到表中。所以我的代碼在語法上是合理的,但我有一個邏輯錯誤。你能爲我解釋一個簡單的OleDbParameter嗎? Thanx – Mordacai1000

回答

1

這是如何使用OleDbParameter的示例。但是,我看不出爲什麼你的代碼不會產生新的流派。

private void newGenreToolStripMenuItem_Click(object sender, EventArgs e) 
{ 
    //(cnSongs)Connection delacred and instantiated elsewhere 
    cnSongs.Open(); 
    try { 

     string input = Interaction.InputBox("Genre ", "New Genre", "Type genre here", -1, -1); 

     Console.WriteLine("User input " + input); 
     string InsertSql = "Insert Into tblGenres (Genre) Values (?)"; 

     OleDbCommand cmdInsert = new OleDbCommand(InsertSql, cnSongs); 

     cmdInsert.Parameters.Add(new OleDbParameter("genre", input)); 

     int i = cmdInsert.ExecuteNonQuery(); 
     Console.WriteLine("Inseted " + i.toString() + " row(s)"); 
    } finally { 
     cnSongs.Close(); 
    } 
} 
+0

It Works!我現在明白了。我們最近纔開始使用數據庫,所以我對這個領域還是有點新的。非常感謝您的輸入 – Mordacai1000

+0

沒問題。您可能不希望成品中的「Console.WriteLine」語句。 – Laurence

相關問題