将 SQL 表读入 C# 数据表
本文关键字:数据表 SQL | 更新日期: 2023-09-27 17:56:58
我已经读过很多关于将数据表插入SQL表的文章,但是有没有一种简单的方法可以将SQL表拉入.NET DataTable?
在这里,试一试(这只是一个伪代码)
using System;
using System.Data;
using System.Data.SqlClient;
public class PullDataTest
{
// your data table
private DataTable dataTable = new DataTable();
public PullDataTest()
{
}
// your method to pull data from database to datatable
public void PullData()
{
string connString = @"your connection string here";
string query = "select * from table";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
// create data adapter
SqlDataAdapter da = new SqlDataAdapter(cmd);
// this will query your database and return the result to your datatable
da.Fill(dataTable);
conn.Close();
da.Dispose();
}
}
var table = new DataTable();
using (var da = new SqlDataAdapter("SELECT * FROM mytable", "connection string"))
{
da.Fill(table);
}
很多方法。
使用数据适配器上的 ADO.Net 并使用填充来获取数据表:
using (SqlDataAdapter dataAdapter
= new SqlDataAdapter ("SELECT blah FROM blahblah ", sqlConn))
{
// create the DataSet
DataSet dataSet = new DataSet();
// fill the DataSet using our DataAdapter
dataAdapter.Fill (dataSet);
}
然后,您可以从数据集中获取数据表。
未使用投票答案数据集中的注释,(它出现在我的答案之后)它确实如此
// create data adapter
SqlDataAdapter da = new SqlDataAdapter(cmd);
// this will query your database and return the result to your datatable
da.Fill(dataTable);
哪个比我的更可取。
我强烈建议查看实体框架...使用数据表和数据集不是一个好主意。它们没有类型安全,这意味着调试只能在运行时完成。使用强类型集合(可以通过使用LINQ2SQL或实体框架获得),您的生活将轻松得多。
编辑:也许我不清楚:数据表=好,数据集=恶。如果您使用的是 ADO.Net 那么您可以使用这两种技术(EF,linq2sql,dapper,nhibernate,orm of the month),因为它们通常位于 ado.net 之上。您获得的优势是,只要您通过利用代码生成具有适当的抽象级别,您就可以更轻松地更新模型,因为您的架构会发生变化。
ado.net 适配器使用公开数据库类型信息的提供程序,例如默认情况下它使用 sql 服务器提供程序,您还可以插入 - 例如 - devart postgress 提供程序,并且仍然可以访问类型信息,然后允许您如上所述使用您选择的 orm(几乎无痛 - 有一些怪癖) - 我相信Microsoft也提供了一个 oracle 提供程序。这样做的全部目的是尽可能从数据库实现中抽象出来。
独立于供应商的版本,完全依赖于 ADO.NET 接口; 2 种方式:
public DataTable Read1<T>(string query) where T : IDbConnection, new()
{
using (var conn = new T())
{
using (var cmd = conn.CreateCommand())
{
cmd.CommandText = query;
cmd.Connection.ConnectionString = _connectionString;
cmd.Connection.Open();
var table = new DataTable();
table.Load(cmd.ExecuteReader());
return table;
}
}
}
public DataTable Read2<S, T>(string query) where S : IDbConnection, new()
where T : IDbDataAdapter, IDisposable, new()
{
using (var conn = new S())
{
using (var da = new T())
{
using (da.SelectCommand = conn.CreateCommand())
{
da.SelectCommand.CommandText = query;
da.SelectCommand.Connection.ConnectionString = _connectionString;
DataSet ds = new DataSet(); //conn is opened by dataadapter
da.Fill(ds);
return ds.Tables[0];
}
}
}
}
我做了一些性能测试,第二种方法总是优于第一种方法。
Stopwatch sw = Stopwatch.StartNew();
DataTable dt = null;
for (int i = 0; i < 100; i++)
{
dt = Read1<MySqlConnection>(query); // ~9800ms
dt = Read2<MySqlConnection, MySqlDataAdapter>(query); // ~2300ms
dt = Read1<SQLiteConnection>(query); // ~4000ms
dt = Read2<SQLiteConnection, SQLiteDataAdapter>(query); // ~2000ms
dt = Read1<SqlCeConnection>(query); // ~5700ms
dt = Read2<SqlCeConnection, SqlCeDataAdapter>(query); // ~5700ms
dt = Read1<SqlConnection>(query); // ~850ms
dt = Read2<SqlConnection, SqlDataAdapter>(query); // ~600ms
dt = Read1<VistaDBConnection>(query); // ~3900ms
dt = Read2<VistaDBConnection, VistaDBDataAdapter>(query); // ~3700ms
}
sw.Stop();
MessageBox.Show(sw.Elapsed.TotalMilliseconds.ToString());
Read1
在眼睛上看起来更好,但数据适配器性能更好(不要混淆一个数据库优于另一个数据库,查询都是不同的)。不过,两者之间的差异取决于查询。原因可能是Load
添加行时需要从文档中逐行检查各种约束(这是DataTable
的方法),而Fill
是在专门为此设计的DataAdapters上 - 快速创建数据表。
居中模型:您可以在任何地方使用它!
你只需要调用下面的格式从你的函数到这个类
DataSet ds = new DataSet();
SqlParameter[] p = new SqlParameter[1];
string Query = "Describe Query Information/either sp, text or TableDirect";
DbConnectionHelper dbh = new DbConnectionHelper ();
ds = dbh. DBConnection("Here you use your Table Name", p , string Query, CommandType.StoredProcedure);
就是这样。这是完美的方法。
public class DbConnectionHelper {
public DataSet DBConnection(string TableName, SqlParameter[] p, string Query, CommandType cmdText) {
string connString = @ "your connection string here";
//Object Declaration
DataSet ds = new DataSet();
SqlConnection con = new SqlConnection();
SqlCommand cmd = new SqlCommand();
SqlDataAdapter sda = new SqlDataAdapter();
try {
//Get Connection string and Make Connection
con.ConnectionString = connString; //Get the Connection String
if (con.State == ConnectionState.Closed) {
con.Open(); //Connection Open
}
if (cmdText == CommandType.StoredProcedure) //Type : Stored Procedure
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = Query;
if (p.Length > 0) // If Any parameter is there means, we need to add.
{
for (int i = 0; i < p.Length; i++) {
cmd.Parameters.Add(p[i]);
}
}
}
if (cmdText == CommandType.Text) // Type : Text
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = Query;
}
if (cmdText == CommandType.TableDirect) //Type: Table Direct
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = Query;
}
cmd.Connection = con; //Get Connection in Command
sda.SelectCommand = cmd; // Select Command From Command to SqlDataAdaptor
sda.Fill(ds, TableName); // Execute Query and Get Result into DataSet
con.Close(); //Connection Close
} catch (Exception ex) {
throw ex; //Here you need to handle Exception
}
return ds;
}
}
如果使用最新版本的 C#(版本 8 之后),代码将变得更加简单,因为 using 语句不需要大括号。
var table = new DataTable();
using var da = new SqlDataAdapter(sql, connectionString);
da.Fill(table);