我在本地磁盘上有一个大的XML文件(150mb范围),并使用ADO.NET将其放入nvarchar(max)列中。代码看起来是这样的(经过大量编辑,所以只留下代码的相关部分):
using ( var fileStream = new FileStream( myfile , FileMode.Open , FileAccess.Read , FileShare.Read ) )
{
// prep sqlconnection...
sqlCon.Open();
var sqlCommand = new SqlCommand();
sqlCommand.Connection = sqlCon;
sqlCommand.CommandType = CommandType.StoredProcedure;
sqlCommand.CommandText = "[dbo].[bigsproc]";
var param1 = new SqlParameter( "@doc" , SqlDbType.NVarChar , Int32.MaxValue );
param1.Value = new SqlXml( fileStream );
sqlCommand.Parameters.Add( param1 );
var syncResult = sqlCommand.ExecuteNonQuery();
我遇到这个问题:
ExceptionBody:System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.
at System.IO.MemoryStream.set_Capacity(Int32 value)
at System.IO.MemoryStream.EnsureCapacity(Int32 value)
at System.IO.MemoryStream.Write(Byte[] buffer, Int32 offset, Int32 count)
at System.Xml.XmlEncodedRawTextWriter.EncodeChars(Int32 startOffset, Int32 endOffset, Boolean writeAllToStream)
at System.Xml.XmlEncodedRawTextWriter.FlushBuffer()
at System.Xml.XmlEncodedRawTextWriter.RawText(Char* pSrcBegin, Char* pSrcEnd)
at System.Xml.XmlEncodedRawTextWriter.RawText(String s)
at System.Xml.XmlEncodedRawTextWriter.WriteStartElement(String prefix, String localName, String ns)
at System.Xml.XmlWellFormedWriter.WriteStartElement(String prefix, String localName, String ns)
at System.Xml.XmlWriter.WriteNode(XmlReader reader, Boolean defattr)
at System.Data.SqlTypes.SqlXml.CreateMemoryStreamFromXmlReader(XmlReader reader)
at System.Data.SqlTypes.SqlXml..ctor(XmlReader value)
at System.Data.SqlClient.SqlParameter.CoerceValue(Object value, MetaType destinationType)
at System.Data.SqlClient.SqlParameter.GetCoercedValue()
at System.Data.SqlClient.SqlParameter.Validate(Int32 index, Boolean isCommandProc)
at System.Data.SqlClient.SqlCommand.SetUpRPCParameters(_SqlRPC rpc, Int32 startCount, Boolean inSchema, SqlParameterCollection parameters)
at System.Data.SqlClient.SqlCommand.BuildRPC(Boolean inSchema, SqlParameterCollection parameters, _SqlRPC& rpc)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
将这种基于磁盘的大型XML放入远程DB服务器的最佳方法是什么?
谢谢。
当对象没有被处理时,就会发生内存溢出异常,就像您看到SQL连接对象不在Using语句中。SqlCommand类也是IDisposable。
这可能不是每次都会出现内存溢出崩溃的问题。但当内存溢出时,问题肯定会出现。。。