关于C#操作Access数据库,SqlServer与Access数据库之间数据传递使用总结

温故而知新~~

下面是Access配置文件,选择符合的下载

Access数据库12.0配置包_32.exe 下载

Access数据库12.0配置包_X64.exe 下载

首先基础的:C#连接Access数据库,方法与连接Sql类似。

AccPath:Access数据库的路径
 string ConAcc = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + AccPath + "; Jet OLEDB:Database Password=密码";

OleDbCommand odC= new OleDbCommand("", new OleDbConnection(ConAcc));
odC.Connection.Open();
//赋值,Access这种赋值方式要注意先后顺序,否则会数据错乱,这是要注意的
odC.Parameters.AddWithValue("@FilePath", strFileInfoPath);//列名,值 odC.Parameters.AddWithValue("@FileCreateTime", strDTC); odC.Parameters.AddWithValue("@EqpID", TbEqpID.Text);

odC.CommandText="";//accsss执行语句
odC.ExecuteNonQuery();//执行(Update,insert,delete)
//如果是查询的话(Select)
  OleDbDataReader ODR = odC.ExecuteReader();
//读一行数据
 if(ODR.Read())
{
string Result=ODR["列名"].ToString();
}
ODR.Close();
//如果是多行记录就用while
while(ODR.Read()){

}
ODR.Close();
odC.Connection.Close();

SqlServer读取Access数据

注意点:读取的Access文件必须在服务器上,可以先将Access数据库上传到服务器,然后再读取。

后续会介绍FTP上传文件的方法。

 SqlCommand sqlC = new SqlCommand("", new SqlConnection(fMain.ConStr));
            sqlC.Connection.Open();
//开启互通权限
   sqlC.CommandText = "exec sp_configure 'show advanced options',1 "
           + " reconfigure "
           + " exec sp_configure 'Ad Hoc Distributed Queries',1 "
           + " reconfigure ";
            sqlC.ExecuteNonQuery();

   sqlC.CommandText = " insert into dbo.[服务器目标表]  SELECT * "
           + " FROM OpenDataSource( 'Microsoft.ACE.OLEDB.12.0', "
           + " 'Data Source=" + (Access地址) + ";Persist Security Info=False;Jet OLEDB:Database Password=密码')...[Access表名]  ";

 sqlC.ExecuteNonQuery();
//关闭互通权限,不关闭会有安全隐患
  sqlC.CommandText = "exec sp_configure 'Ad Hoc Distributed Queries',0 "
           + "reconfigure "
           + "exec sp_configure 'show advanced options',0 "
           + "reconfigure";
            sqlC.ExecuteNonQuery();
 sqlC.Connection.Close();

Access读取Sqlserver数据

这边采用的方法时将Sqlserver数据读取到DataTable中,然后将DateTable中数据插入Access

我封装了一个方法如下:

 /// <summary>
        /// 
        /// </summary>
        /// <param name="DT">DateTable</param>
        /// <param name="AccessTableName">Access表名</param>
        /// <param name="ConAcc">Access连接字符串</param>
        public void Insett(DataTable DT,string AccessTableName,string ConAcc)
        {
            OleDbCommand odC = new OleDbCommand("", new OleDbConnection(ConAcc));
            odC.Connection.Open();
                        List<string> LSCName = new List<string>();
                        StringBuilder strColumns = new StringBuilder();
                        foreach (DataColumn item in DT.Columns)//获取列名
                        {
                            LSCName.Add(item.ToString());
                            strColumns.Append(item.ToString() + ",");
                        }

                        for (int i = 0; i < DT.Rows.Count; i++)
                        {
                            if (i == 0)//建表
                            {
                                StringBuilder strCommand = new StringBuilder();
                                for (int j = 0; j < DT.Columns.Count; j++)
                                {
                                    strCommand.Append("'" + DT.Rows[i][j] + "' AS " + LSCName[j] + ",");
                                }
                                odC.CommandText = "select " + strCommand.ToString().Substring(0, strCommand.ToString().Length - 1) + " into " + AccessTableName;
                                odC.ExecuteNonQuery();
                                //TSPB.Value++;
                            }
                            if (i > 0)//插入数据
                            {
                                StringBuilder strCommand = new StringBuilder();
                                for (int j = 0; j < DT.Columns.Count; j++)
                                {
                                    strCommand.Append("'" + DT.Rows[i][j] + "',");
                                }
                                odC.CommandText = "insert into " + AccessTableName + " (" + strColumns.ToString().Substring(0, strColumns.ToString().Length - 1) + ") select " + strCommand.ToString().Substring(0, strCommand.ToString().Length - 1);
                                odC.ExecuteNonQuery();

                            }
                  
                        }
                    odC.Connection.Close();
            }

 

using System; using System.Data; using System.Configuration; using System.Data.OleDb; namespace xxxxx { /// <summary> /// Access数据库访问类 /// </summary> public class DataAccess { private static OleDbConnection conn = new OleDbConnection(); private static OleDbCommand comm = new OleDbCommand(); private static string asscessPath = @".\PoliScan.mdb"; /// <summary> /// 设置Access数据库路径 /// </summary> /// <param name="path">完整的路径字符串</param> public static void SetAccessPath(string path) { asscessPath = path; } /// <summary> /// 打开数据库 /// </summary> /// <returns>成功返回 true;失败返回 false;异常时抛出异常</returns> public static bool OpenConnection() { bool retval = false; if (conn.State != ConnectionState.Open) { conn.ConnectionString = @"Provider=Microsoft.Jet.OleDb.4.0;Data Source=" + asscessPath; comm.Connection = conn; try { conn.Open(); if (conn.State == ConnectionState.Open) { retval = true; } } catch (Exception e) { throw new Exception(e.Message); } ............................ ............................ using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Data.OleDb; using System.Data.SqlClient; /// <summary> /// DataBase 的摘要说明 /// </summary> public class DataBase : IDisposable { public DataBase() { // // TODO: 在此处添加构造函数逻辑 // } private SqlConnection con; //创建连接对象 #region 打开数据库连接 /// <summary> /// 打开数据库连接. /// </summary> private void Open() { // 打开数据库连接 if (con == null) { con = new SqlConnection("Data Source = . ;Database = CET ;Integrated Security = SSPI "); } if (con.State == System.Data.ConnectionState.Closed) con.Open(); }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值