View code
Using system; using system. collections. generic; using system. LINQ; using system. text; using system. data. SQL; using system. data; using system. data. oledb; namespace accessvisit {class program {static void main (string [] ARGs) {datatable dt = new datatable (); DT. columns. add ("name", typeof (string); DT. columns. add ("Age", typeof (INT); DT. columns. add ("sex", typeof (string); DT. rows. add ("John", 22, "male"); DT. rows. add ("Xiao Li", 22, "Female"); DT. rows. add ("Xiaohong", 22, "male"); DT. rows. add ("James", 22, "female"); // you must first create oledbconnection conn = new oledbconnection (@ "provider = Microsoft. jet. oledb.4.0; Data Source = c: \ Documents ents and Settings \ Administrator \ Desktop \ access. mdb "); If (Conn. state! = Connectionstate. open) {Conn. open ();} oledbtransaction Tx = Conn. begintransaction (); oledbcommand cmd = new oledbcommand (); cmd. connection = conn; cmd. transaction = TX; try {for (INT I = 0; I <DT. rows. count; I ++) {stringbuilder sqlstr = new stringbuilder (); sqlstr. append ("insert into people values ('" + dt. rows [I] [0]. tostring () + "',"); sqlstr. append (DT. rows [I] [1]. tostring () + ", '"); sqlstr. append (DT. rows [I] [2]. tostring () + "')"); cmd. commandtext = sqlstr. tostring (); cmd. executenonquery ();} Tx. commit ();} catch (oledbexception e) {Tx. rollback (); throw new exception (E. message);} finally {If (Conn. state = connectionstate. open) {Conn. close ();}}}}}