Access Db (.mdb) 연결하기 (feat.C#)



1. DB 연결하기

1
2
3
4
5
6
7
// it's your DB file path:
// ApplicationEXEPath\Test.mdb
var DBPath = Application.StartupPath + "\\Test.mdb";
 
conn = new OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0;"
    + "Data Source=" + DBPath);
conn.Open();
cs


1.1 DB 연결하기 (.accdb파일)

1
2
3
4
string connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\test.accdb;"
OleDbConnection conn = new OleDbConnection(connStr);
conn.Open();
 
cs


2. Insert Query

1
2
3
4
5
6
7
8
// txtInsert.Text:
// INSERT INTO Table_1 (text_col, int_col) VALUES ('Text', 9);
//
// inserts 1 row into Table_1 table
using (OleDbCommand cmd = new OleDbCommand(txtInsert.Text, conn))
{
    cmd.ExecuteNonQuery();
}
cs


3. Select Query

1
2
3
4
5
6
7
8
9
10
11
12
13
14
using (DataTable dt = new DataTable())
{
    // txtSelect.Text:
    // SELECT id, text_col, int_col FROM Table_1
    // or
    // SELECT * FROM Table_1
    //
    // selects all content from table and adds it to datatable binded to datagridview
    using (OleDbDataAdapter adapter = new OleDbDataAdapter(txtSelect.Text, conn))
    {
        adapter.Fill(dt);
    }
    dgvSelect.DataSource = dt;
}
cs


4. Update Querty
1
2
3
4
5
6
7
8
// txtUpdate.Text:
// UPDATE Table_1 SET [text_col]='Updated text', [int_col]=2014 WHERE id=2;
//
// changes 2nd row in Table_1
using (OleDbCommand cmd = new OleDbCommand(txtUpdate.Text, conn))
{
    cmd.ExecuteNonQuery();
}
cs

5. Delete Query

1
2
3
4
5
6
7
8
// txtDelete.Text:
// DELETE FROM Table_1 WHERE id=2;
//
// removes 2nd row in Table_1
using (OleDbCommand cmd = new OleDbCommand(txtDelete.Text, conn))
{
    cmd.ExecuteNonQuery();
}
cs


출처 : https://www.codeproject.com/Tips/858771/MS-Access-mdb-plus-Csharp-SELECT-INSERT-DELETE-and

출처 : http://www.csharpstudy.com/Practical/Prac-accessdb.aspx

+ Recent posts