zoukankan      html  css  js  c++  java
  • ADO.NET获取数据(DataSet)同时获取表的架构

    普通的ADO.NET获取DataSet的写法如下:

    using System.Configuration;
    using System.Data;
    using System.Data.SqlClient;
    public class SQLHelper
    {
        private static readonly string ConnectionString = ConfigurationManager.ConnectionStrings["Default"].ConnectionString;
    
        public static DataSet GetDataSet(string sql)
        {
            using (SqlConnection conn =new SqlConnection(ConnectionString))
            {
                SqlCommand cmd = new SqlCommand(sql, conn);
                SqlDataAdapter adapter = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                conn.Open();
                adapter.Fill(ds);
                return ds;
            }
        }
    }
    View Code
    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
      <connectionStrings>
        <add name="Default" connectionString="Data Source=.;Initial Catalog=EFDb;Integrated Security=true"/>
      </connectionStrings>
    </configuration>
    View Code

    这里需要获取DataTable的主键信息,调试时发现没有主键信息,而实际数据库中是有主键(Id)

    此时需要给SqlDataAdapter设置属性MissingSchemaAction为System.Data.MissingSchemaAction.AddWithKey

    修改后的SQLHelper为

    using System.Configuration;
    using System.Data;
    using System.Data.SqlClient;
    public class SQLHelper
    {
        private static readonly string ConnectionString = ConfigurationManager.ConnectionStrings["Default"].ConnectionString;
    
        public static DataSet GetDataSet(string sql)
        {
            using (SqlConnection conn =new SqlConnection(ConnectionString))
            {
                SqlCommand cmd = new SqlCommand(sql, conn);
                SqlDataAdapter adapter = new SqlDataAdapter(cmd);
                adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
                DataSet ds = new DataSet();
                conn.Open();
                adapter.Fill(ds);
                return ds;
            }
        }
    }

  • 相关阅读:
    Python入门6 —— 流程控制
    Python入门5 —— 基本运算符
    Python入门4 —— 输入与输出
    实用小工具 下载链接
    [笔记] BGP in the Data Center (O'Reilly 2017)
    数据中心网络:Spine-Leaf 架构设计综述(2016)
    Using Open vSwitch* with DPDK for Inter-VM NFV Applications
    hung_task
    TCPDUMP and IPv6 and perf trace --no-syscalls
    Go非缓冲/缓冲/双向/单向通道
  • 原文地址:https://www.cnblogs.com/godbell/p/8051418.html
Copyright © 2011-2022 走看看