2012-01-26 6 views
-1

これはAccessデータベースに接続して作業するC#コードです。.NET OleDbConnectionオブジェクトとそのConnectionStringプロパティを正しく初期化する方法

using System.Data.OleDb; 

var cb = new OleDbCommandBuilder(da); 

DataRow dRow = ds1.Tables["Customer"].NewRow(); 

dRow[0] = textBox1.Text; 
dRow[1] = textBox2.Text; 
dRow[2] = textBox3.Text; 

ds1.Tables["Customer"].Rows.Add(dRow); 

da.Update(ds1, "Customer"); 

con.Close(); 

MessageBox.Show("Entry added"); 


しかしラインda.Update(ds1,"Customer");、例外がスローされます:

ConnectionStringプロパティが初期化されていません。

+4

ここで、接続オブジェクトを初期化していますか?私たちを見せてください。しかし、おそらく接続文字列を設定していないでしょう。 – gabsferreira

+2

接続文字列の問題の場合は、[here](http://www.connectionstrings.com/access-2007)を参照してください。 –

答えて

1

私はあなたの質問にあまりうまく対応していませんが、何をしようとしているのかを理解するのに役立つサンプルコードがあります。

わかりやすくするために、データベースの名前は「MyDb.accdb」で、「Customer」という名前のテーブルには「Name」と「Phone」の2つのフィールドがあります。この例では、データベースが実行可能ファイルと同じディレクトリに存在することを前提としています。

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(); 
    } 
} 
関連する問題