Andy 胡

导航

C#操作Access

using System;
using System.Data.OleDb;
class Program {
    static void Main(string[] args) {
        const string ACCESS_PATH = "../MyDB.accdb";
        // Persist Security Info:是否保存安全信息    
        // True表示保存,False表示不保存    
        const string connStr = "Provider=Microsoft.ACE.oledb.12.0;Data Source="
            + ACCESS_PATH + "; Persist Security Info=False";

        //声明数据库相关变量    
        OleDbConnection _conn = null;
        OleDbCommand _cmd = null;
        OleDbDataReader _reader = null;
        try
        {
            //链接数据库    

            _conn = new OleDbConnection(connStr);
            _conn.Open();
            string sql = "select * from t1";
            _cmd = new OleDbCommand(sql, _conn);
            //读取数据    
            _reader = _cmd.ExecuteReader();

            if (_reader.HasRows)
            {
                while (_reader.Read())
                {
                    string s = String.Format("取到内容:{0}  {1}  {2}", _reader.GetInt32(0), _reader.GetString(1), _reader["pwd"]);
                    Console.WriteLine(s);
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        finally
        {
            if (_reader != null)
            {
                _reader.Close();
                _reader = null;
            }

            if (_conn != null)
            {
                _conn.Close();
                _conn = null;
            }
        }
        Console.ReadKey();
    }
}

更新数据:

try
{
    //链接数据库
    _conn = new OleDbConnection(connStr);
    _conn.Open();
    string sql = "update t1 set pwd = '1' where id = 1";
    _cmd = new OleDbCommand(sql, _conn);
    //读取数据    
    int n = _cmd.ExecuteNonQuery();
    Console.WriteLine(n + "行受影响");
}

 

posted on 2017-03-26 02:18  talkwah  阅读(213)  评论(0编辑  收藏  举报