我有以下辅助函数,用于基于SQL SELECT对SQL Server数据库加载DataTable
(稍微简化):
static private DataTable GetData_(string connectionString, string sqlSelect, bool doFillSchema = false)
{
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlDataAdapter adapter = new SqlDataAdapter(sqlSelect, connection))
{
DataTable table = new DataTable();
if (doFillSchema)
adapter.FillSchema(table, SchemaType.Mapped);
adapter.Fill(table);
return table;
}
}
后一个目标是将返回的table
传递给另一个应该将内容导出到DBF表的函数(即CREATE TABLE并使用与引擎的不同功能相关的一些更正来编写内容)。
问题是该实现会将原始的numeric(10, 2)
列说明类型更改为架构中的Decimal
。我想保留原文。
如果我理解得很好,我可能需要使用原始模式获得另一个DataTable schemaTable
(在适配器更改列类型之前)。我的想法是修改这个功能:
static private DataTable GetData_(string connectionString, string sqlSelect,
bool doFillSchema, ref DataTable schemaTable)
{
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlDataAdapter adapter = new SqlDataAdapter(sqlSelect, connection))
{
DataTable table = new DataTable();
if (doFillSchema)
??? fill the schema table
adapter.Fill(table);
return table;
}
}
应该如何实现功能? SqlDataAdapter
是否应该用于此目的?或者应该以不同的方式完成?
答案 0 :(得分:0)
所以,我有这个自我回答。如果您有更好的解决方案,我将很乐意接受它。 ;)
static private DataTable GetData_(string connectionString, string sqlSelect, Hashtable arg,
bool doFillSchema, ref DataTable schemaTable)
{
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(sqlSelect, connection))
{
connection.Open();
// If we want the schema, do the extra step.
if (doFillSchema)
{
using (SqlDataReader reader = command.ExecuteReader(CommandBehavior.KeyInfo))
schemaTable = reader.GetSchemaTable();
}
// Use the adapter to fill the result table..
using (SqlDataAdapter adapter = new SqlDataAdapter(command))
{
DataTable table = new DataTable();
// Set the SELECT arguments.
if (arg != null)
{
foreach (DictionaryEntry item in arg)
{
adapter.SelectCommand.Parameters.AddWithValue(item.Key.ToString(), item.Value);
}
}
// Get the result of the SQL query.
adapter.Fill(table);
return table;
}
}
}