ADO.NET获取数据(DataSet)同时获取表的架构实例
程序员文章站
2022-09-02 11:54:51
普通的ado.net获取dataset的写法如下:
using system.configuration;
using system.data;
using...
普通的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; } } }
<?xml version="1.0" encoding="utf-8" ?> <configuration> <connectionstrings> <add name="default" connectionstring="data source=.;initial catalog=efdb;integrated security=true"/> </connectionstrings> </configuration>
这里需要获取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; } } }
以上这篇ado.net获取数据(dataset)同时获取表的架构实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。