我並不太在意你的問題,但這裏有一些示例代碼可以幫助你找出你正在嘗試做的任何事情。
爲了清楚起見:數據庫名爲「MyDb.accdb」,並有一個名爲「Customer」的表,其中有兩個字段「Name」和「Phone」。這個例子假設數據庫和可執行文件位於同一個目錄中。
private void AddCustomer(string customerName, string customerPhone)
{
string name = customerName;
string phone = customerPhone;
// An easy way to determine the connection string to your database is to open the database from Visual Studio's 'Server Explorer'.
// Then, from Server Explorer, view the Properties of the database - in the Properties you will see the "Connection String".
// You can/should replace the arbitrary part of the path with "|DataDirectory|".
string connString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|MyDb.accdb;Persist Security Info=True";
// Create your sql query in a string variable
string cmdText = string.Format("INSERT INTO Customer(Name, Phone) VALUES('{0}','{1}');", name, phone);
// Use the 'using' statement on your connection so that the resource is managed properly
using (System.Data.OleDb.OleDbConnection connection = new System.Data.OleDb.OleDbConnection(connString))
{
// Here's where/how we fire off the INSERT statement
OleDbCommand cmd = new OleDbCommand(cmdText, connection);
connection.Open();
cmd.ExecuteNonQuery();
}
}
來源
2012-01-26 19:54:48
Jed
你在哪裏初始化連接對象?告訴我們,但可能你沒有爲它設置任何連接字符串。 – gabsferreira
如果是連接字符串問題,請查看[here](http://www.connectionstrings.com/access-2007)以獲取示例。 –