c#访问access数据库

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("小王",22,"");
DT.Rows.Add("小李", 22, "");
DT.Rows.Add("小红", 22, "");
DT.Rows.Add("小明", 22, "");

//Access数据库需要先建立
OleDbConnection conn = new OleDbConnection(@"provider=microsoft.jet.oledb.4.0; Data Source=C:\Documents and Settings\Administrator\桌面\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();
}
}
}
}
}
posted @ 2012-10-12 16:35  尼姑哪里跑  阅读(213)  评论(0编辑  收藏  举报