ADO.NET获取数据(DataSet)同时获取表的架构

2018-06-17 22:30:08来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折

普通的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;
        }
    }
}

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:学习Memcached:1基本配置与安装

下一篇:ADO调用分页查询存储过程