zoukankan      html  css  js  c++  java
  • 访问Access数据库(有多个数据库时 体现多态)

    如果想编写单机版MIS、小型网站等对数据库性能要求不高的系统,又不想安装SQLServer,可以使用Access(MDAC),只要一个mdb文件就可以了。
    使用Access创建mdb文件,建表。
    OleDbConnection、OleDbCommand……,用法和SqlServer差不多。和SQLServer的区别:
    一些复杂的SQL函数、语法Access不支持。
    参数化查询不使用@name占位符,而是使用?,new OleDbParameter("?", guid.ToString(),要按照SQL语句中?的顺序添加OleDbParameter。
    name和password都是保留字,最好不要用做列名,用的话加上[]

    复制代码
        string str = ConfigurationManager.ConnectionStrings["connstr"].ConnectionString;
        string pName = ConfigurationManager.ConnectionStrings["connstr"].ProviderName;
    
        IDbConnection conn;
        if (pName == "SQLServer")
        {
          conn = new SqlConnection(str);
        }
        else if (pName == "Access")
        {
          conn = new OleDbConnection(str);
        }
        else
        {
          MessageBox.Show("无效的ProviderName!");
          return;
        }
    
        using (conn)    // 体现多态 ,谁也不知道conn是SQL的还是Access的
        {
          if (conn.State == ConnectionState.Closed)
          {
            conn.Open();
          }
        
          using (IDbCommand cmd = conn.CreateCommand())
          {
            cmd.CommandText = "Insert into T_Person(Name,Age) Values('" + txtName.Text + "'," + Convert.ToInt32(txtAge.Text) + ")";
            if (Convert.ToInt32(cmd.ExecuteNonQuery()) > 0)
            {
              MessageBox.Show("增加成功!");
            }
          }
        }
    复制代码
  • 相关阅读:
    python--Tuple类型
    python--List类型
    剑指offer--数组中重复的数字
    Assignment HDU
    kuangbin 并查集
    Girls and Boys-hdu 1068
    Computer HDU
    Terrorist’s destroy HDU
    Roads in the North POJ
    Labyrinth POJ
  • 原文地址:https://www.cnblogs.com/yezuhui/p/6842755.html
Copyright © 2011-2022 走看看