프로그래밍/c# & VB 등
[c#] mdb 특정 테이블의 컬럼 값을 불러오는 소스
낼은어떻게
2016. 4. 4. 10:22
INSERT into query를 할려면 해당 컬럼 값을 일일히 기록해야 되는 경우가 있습니다. 그러한데 그 테이블 전체에 값을 넣을때 .. 그 컬럼값이 많으면 일일히 적어서 코딩하기가 귀찮은것이 사살입니다.
이럴때 사용하면 좋은 코드입니다.
'
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 | using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.OleDb; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace test_datasetupdate { public partial class Form1 : Form { string db_path = @"c:\test.mdb"; public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { } private void Form1_Load(object sender, EventArgs e) { DataConn conn = new DataConn(); DataSet ds = new DataSet(); string sql = @"select * from test_table"; ds = conn.GetDataset(sql, db_path); string[] fields = new string[23]; ArrayList arr_rec = new ArrayList(); // test_table의 컬럼수가 23개 입니다.. for (int i = 0; i < ds.Tables[0].Columns.Count; i++) { fields[i] = ds.Tables[0].Columns[i].ToString(); } string str_params = string.Join(",", fields); //string 배열을 하나의 string 변수로 만들어줍니다. 사이사이에 ','를 삽입해주면서 str_params = str_params.Substring(0, str_params.Length - 1); //마지막에 들어가는 ',' 삭제 코드입니다. 이거 없이 그대로 사용하면 oledb error가 납니다. try { DataSet ds1 = new DataSet(); string sql1 = @"select " + str_params + " from test_table"; ds1 = conn.GetDataset(sql1, db_path); dataGridView1.DataSource = ds.Tables[0]; // } catch (Exception E){ MessageBox.Show(E.ToString()); } } class DataConn { public DataSet GetDataset(string sql, string DB_path) { string connStr = conn_str(DB_path); OleDbConnection conn = new System.Data.OleDb.OleDbConnection(connStr); DataSet ds = new DataSet(); OleDbDataAdapter adp = new OleDbDataAdapter(sql, conn); adp.Fill(ds); return ds; } public string conn_str(string db_path) { string connStr = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + db_path + ";Jet OLEDB:Database Password="; return connStr; } } } } | cs |