欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2024-01-13 22:21:04
普通的ADO.NET获取DataSet的写法如下: using System.Configuration; using System.Data; using System.Data.SqlClient; public class SQLHelper { private static readonly ......

普通的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 ADO.NET获取数据数据(DataSet)同时获取表的架构
<?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)

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

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

此时需要给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;
        }
    }
}

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