C# 如何实现IDataReader接口,以便在插入之前处理数据?
我有一个存储过程,它给我一个结果集,它由一个单个列组成,该列包含数百万个未处理的行。我需要使用SqlBulkCopy将这些数据传输到另一台服务器,但问题是我不能简单地执行以下操作:C# 如何实现IDataReader接口,以便在插入之前处理数据?,c#,sqldatareader,sqlbulkcopy,idatareader,C#,Sqldatareader,Sqlbulkcopy,Idatareader,我有一个存储过程,它给我一个结果集,它由一个单个列组成,该列包含数百万个未处理的行。我需要使用SqlBulkCopy将这些数据传输到另一台服务器,但问题是我不能简单地执行以下操作: using (var con = new SqlConnection(sqlConnectionStringSource)) { using (var cmd = new SqlCommand("usp_GetUnprocessedData", con)) { cmd.CommandT
using (var con = new SqlConnection(sqlConnectionStringSource))
{
using (var cmd = new SqlCommand("usp_GetUnprocessedData", con))
{
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
using (var reader = cmd.ExecuteReader())
{
using (var sqlBulk = new SqlBulkCopy(sqlConnectionStringDestination))
{
sqlBulk.DestinationTableName = "BulkCopy";
sqlBulk.BulkCopyTimeout = 0;
sqlBulk.BatchSize = 200000;
sqlBulk.WriteToServer(reader);
}
}
}
}
因为数据根本不会被处理
在我的例子中,结果集的第n行如下所示:
value1_n,value2_n,value3_n
其中,n
只是我介绍的一个下标,用于区分不同的行
在我命名为BulkCopy
的目标表中,我希望:
╔══════════╦══════════╦══════════╗
║ Field1 ║ Field2 ║ Field3 ║
╠══════════╬══════════╬══════════╣
║ Value1_1 ║ Value2_1 ║ Value3_1 ║
║ Value1_2 ║ Value2_2 ║ Value3_2 ║
║ ... ║ ... ║ ... ║
║ Value1_n ║ Value2_n ║ Value3_n ║
╚══════════╩══════════╩══════════╝
我被告知通过IDataReader
接口的实现使用自定义DataReader
,以便在SqlBulkCopy
复制数据之前逐行处理数据,使用EnableStreamingProperty=true
确保内存中只有少量数据,但我不知道从哪里开始。
你能帮我吗?我发现了以下代码项目:。看起来您必须获取csv数据并将其拆分为对象。我用下面的代码修改了代码项目。有许多类型尚未实现,您可能需要实现一些其他方法。也不确定结果值应该是什么类型
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
namespace ConsoleApplication108
{
class Program
{
static void Main(string[] args)
{
}
}
public class MyDataReader : IDataReader
{
private SqlConnection conn { get; set; }
private SqlCommand cmd { get; set; }
private SqlDataReader reader { get; set; }
private DataTable schemaTable { get; set; }
private string data { get; set; }
private object[] arrayData { get; set; }
private IEnumerator<object> m_dataEnumerator { get; set; }
public MyDataReader(string commandText, string connectionString, List<KeyValuePair<string, Type>> columns)
{
conn = new SqlConnection(connectionString);
conn.Open();
cmd = new SqlCommand(commandText, conn);
reader = cmd.ExecuteReader();
schemaTable = new DataTable();
foreach(KeyValuePair<string,Type> col in columns)
{
schemaTable.Columns.Add(col.Key, col.Value);
}
}
public Boolean NextResult()
{
return reader.Read();
}
public int RecordsAffected
{
get { return -1; }
}
public int Depth
{
get { return -1; }
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (disposing)
{
if (m_dataEnumerator != null)
{
m_dataEnumerator.Dispose();
m_dataEnumerator = null;
}
}
}
public Boolean IsClosed {
get { return reader.IsClosed; }
}
public Boolean Read()
{
if (IsClosed)
{
throw new ObjectDisposedException(GetType().Name);
}
else
{
arrayData = reader.GetString(0).Split(new char[] { ',' }).ToArray();
}
return m_dataEnumerator.MoveNext();
}
public DataTable GetSchemaTable()
{
return schemaTable;
}
public void Close()
{
Dispose();
}
public object this[string name]
{
get { throw new NotImplementedException(); }
}
public object this[int i]
{
get { return arrayData[i]; }
}
public int FieldCount
{
get { return arrayData.Length; }
}
public bool IsDBNull(int i)
{
throw new NotImplementedException();
}
public bool GetBoolean(int i)
{
throw new NotImplementedException();
}
public byte GetByte(int i)
{
throw new NotImplementedException();
}
public long GetBytes(int i, long fieldOffset, byte[] buffer, int bufferoffset, int length)
{
throw new NotImplementedException();
}
public char GetChar(int i)
{
throw new NotImplementedException();
}
public long GetChars(int i, long fieldoffset, char[] buffer, int bufferoffset, int length)
{
throw new NotImplementedException();
}
public IDataReader GetData(int i)
{
throw new NotImplementedException();
}
public string GetDataTypeName(int i)
{
throw new NotImplementedException();
}
public DateTime GetDateTime(int i)
{
throw new NotImplementedException();
}
public decimal GetDecimal(int i)
{
throw new NotImplementedException();
}
public double GetDouble(int i)
{
throw new NotImplementedException();
}
public Type GetFieldType(int i)
{
throw new NotImplementedException();
}
public float GetFloat(int i)
{
throw new NotImplementedException();
}
public Guid GetGuid(int i)
{
throw new NotImplementedException();
}
public short GetInt16(int i)
{
throw new NotImplementedException();
}
public int GetInt32(int i)
{
throw new NotImplementedException();
}
public long GetInt64(int i)
{
throw new NotImplementedException();
}
public string GetName(int i)
{
throw new NotImplementedException();
}
public string GetString(int i)
{
throw new NotImplementedException();
}
public int GetValues(object[] values)
{
values = arrayData;
return arrayData.Length;
}
public int GetOrdinal(string name)
{
throw new NotImplementedException();
}
public object GetValue(int i)
{
return arrayData[i];
}
}
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
使用系统数据;
使用System.Data.SqlClient;
命名空间控制台应用程序108
{
班级计划
{
静态void Main(字符串[]参数)
{
}
}
公共类MyDataReader:IDataReader
{
专用SqlConnection连接{get;set;}
私有SqlCommand cmd{get;set;}
私有SqlDataReader读取器{get;set;}
私有数据表模式表{get;set;}
私有字符串数据{get;set;}
私有对象[]arrayData{get;set;}
私有IEnumerator m_数据枚举器{get;set;}
公共MyDataReader(字符串commandText、字符串connectionString、列表列)
{
conn=新的SqlConnection(connectionString);
conn.Open();
cmd=新的SqlCommand(commandText,conn);
reader=cmd.ExecuteReader();
schemaTable=新数据表();
foreach(列中的KeyValuePair列)
{
schemaTable.Columns.Add(col.Key,col.Value);
}
}
公共布尔值NextResult()
{
返回reader.Read();
}
公共int记录受影响
{
获取{return-1;}
}
公共整数深度
{
获取{return-1;}
}
公共空间处置()
{
处置(真实);
总干事(本);
}
私有无效处置(bool处置)
{
如果(处置)
{
if(m_数据枚举器!=null)
{
m_dataEnumerator.Dispose();
m_dataEnumerator=null;
}
}
}
公共图书馆是封闭的{
获取{return reader.IsClosed;}
}
公共布尔读取()
{
如果(已关闭)
{
抛出新的ObjectDisposedException(GetType().Name);
}
其他的
{
arrayData=reader.GetString(0).Split(新字符[]{',}).ToArray();
}
返回m_dataEnumerator.MoveNext();
}
公共数据表GetSchemaTable()
{
返回模式;
}
公众假期结束()
{
处置();
}
公共对象[字符串名称]
{
获取{抛出新的NotImplementedException();}
}
公共对象此[int i]
{
获取{return arrayData[i];}
}
公共整型字段计数
{
获取{return arrayData.Length;}
}
公共布尔IsDBNull(int i)
{
抛出新的NotImplementedException();
}
公共bool GetBoolean(int i)
{
抛出新的NotImplementedException();
}
公共字节GetByte(int i)
{
抛出新的NotImplementedException();
}
公共长GetBytes(int i,long fieldOffset,byte[]buffer,int bufferoffset,int length)
{
抛出新的NotImplementedException();
}
公共字符GetChar(int i)
{
抛出新的NotImplementedException();
}
公共长GetChars(int i,long fieldoffset,char[]buffer,int bufferoffset,int length)
{
抛出新的NotImplementedException();
}
公共IDataReader获取数据(int i)
{
抛出新的NotImplementedException();
}
公共字符串GetDataTypeName(int i)
{
抛出新的NotImplementedException();
}
公共日期时间GetDateTime(int i)
{
抛出新的NotImplementedException();
}
公共十进制GetDecimal(int i)
{
抛出新的NotImplementedException();
}
公共双精度GetDouble(int i)
{
抛出新的NotImplementedException();
}
公共类型GetFieldType(int i)
{
抛出新的NotImplementedException();
}
公共浮点GetFloat(int i)
{
抛出新的NotImplementedException();
}
公共Guid GetGuid(int i)
{
抛出新的NotImplementedException();
}
公共短消息GetInt16(int i)
{
抛出新的NotImplementedException();
}
公共整数GetInt32(整数i)
{
抛出新的NotImplementedException();
}
公共长GetInt64(int i)
{
抛出新的NotImplementedException();
class MyDTO
{
public string Field1{get;set;}
public string Field2{get;set;}
public string Field3{get;set;}
}
public IEnumerable<MyDTO> ReaderToStream(IDataReader reader)
{
while(reader.Read())
{
var line=reader.GetString(0);
var fields=String.Split(",",line);
yield return new MyDTO{Field1=fields[0];Field2=fields[1];Field3=fields[2]};
}
}
using (var con = new SqlConnection(sqlConnectionStringSource))
{
...
using (var reader = cmd.ExecuteReader())
{
var recordStream=ReaderToStream(reader);
using(var rd=ObjectReader(recordStream))
using (var sqlBulk = new SqlBulkCopy(sqlConnectionStringDestination))
{
...
sqlBulk.WriteToServer(rd);
}
}
}
class ReaderWrapper:IDataReader
{
private readonly IDataReader _inner ;
public ReaderWrapper(IDataReader inner)
{
_inner = inner;
}
}
class ReaderWrapper:IDataReader
{
private readonly IDataReader _inner ;
public ReaderWrapper(IDataReader inner)
{
_inner = inner;
}
public object this[int i] => _inner[i];
public object this[string name] => _inner[name];
public int Depth => _inner.Depth;
public bool IsClosed => _inner.IsClosed;
public int RecordsAffected => _inner.RecordsAffected;
public int FieldCount => _inner.FieldCount;
public void Close() => _inner.Close();
public void Dispose() => _inner.Dispose();
public bool GetBoolean(int i) => _inner.GetBoolean(i);
public byte GetByte(int i) => _inner.GetByte(i);
public long GetBytes(int i, long fieldOffset, byte[] buffer, int bufferoffset, int length) => _inner.GetBytes(i, fieldOffset, buffer, bufferoffset, length);
public char GetChar(int i) => _inner.GetChar(i);
public long GetChars(int i, long fieldoffset, char[] buffer, int bufferoffset, int length) => _inner.GetChars(i, fieldoffset, buffer, bufferoffset, length);
public IDataReader GetData(int i) => _inner.GetData(i);
public string GetDataTypeName(int i) => _inner.GetDataTypeName(i);
public DateTime GetDateTime(int i) => _inner.GetDateTime(i);
public decimal GetDecimal(int i) => _inner.GetDecimal(i);
public double GetDouble(int i) => _inner.GetDouble(i);
public Type GetFieldType(int i) => _inner.GetFieldType(i);
public float GetFloat(int i) => _inner.GetFloat(i);
public Guid GetGuid(int i) => _inner.GetGuid(i);
public short GetInt16(int i) => _inner.GetInt16(i);
public int GetInt32(int i) => _inner.GetInt32(i);
public long GetInt64(int i) => _inner.GetInt64(i);
public string GetName(int i) => _inner.GetName(i);
public int GetOrdinal(string name) => _inner.GetOrdinal(name);
public DataTable GetSchemaTable() => _inner.GetSchemaTable();
public string GetString(int i) => _inner.GetString(i);
public object GetValue(int i) => _inner.GetValue(i);
public int GetValues(object[] values) => _inner.GetValues(values);
public bool IsDBNull(int i) => _inner.IsDBNull(i);
public bool NextResult() => _inner.NextResult();
public bool Read() => _inner.Read();
}
private string[] _values;
public bool Read()
{
var ok = _inner.Read();
if (ok)
{
//It *could be null*
if (_inner.IsDBNull(0))
{
//What to do? Store an empty array for now
_values = new string[0];
}
var fieldValue = _inner.GetString(0);
_values= fieldValue.Split(',');
}
return ok;
}
public int FieldCount => _values.Length;
public string GetString(int ordinal) => _values[ordinal];
public object GetValue(int ordinal)=> _values[ordinal];
//What if we have more values than expected?
public int GetValues(object[] values)
{
if (_values.Length > 0)
{
Array.Copy(_values, values,_values.Length);
return _values.Length;
}
return 0;
}
public string GetName(int ordinal) => $"Field{ordinal}";
public int GetOrdinal(string name) => int.Parse(name.Substring(5));
public object this[string name] => _values[GetOrdinal(name)];
public object this[int i] => _values[i];
public bool IsDBNull(int i)
{
//Covers the "null" case too, when `Length` is 0
if (i>_values.Length-1)
{
return true;
}
return _inner.IsDBNull(i);
}
public DataTable GetSchemaTable() => throw new NotImplementedException();
interface IReaderWrapper:IDataReader
{
//Gives access to the wrapped reader in the concrete classes
abstract IDataReader Inner();
override object this[int i] => Inner()[i];
override object this[string name] => Inner()[name];
override int Depth => Inner().Depth;
override bool IsClosed => Inner().IsClosed;
...
}
class SplitterWrapper:IReaderWrapper
{
private readonly IDataReader _inner ;
public SplitterWrapper(IDataReader inner)
{
_inner = inner;
}
IDataReader Inner()=> _inner;
string[] _values;
public object this[int i] => _values[i];
...
}