C# 从文本列中检索数据
// 从文本列中检索数据
// RetrieveText.cs
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.IO;
namespace Ch18
{
class RetrieveText
{
string textFile = null;
char[] textChars = null;
SqlConnection conn = null;
SqlCommand cmd = null;
SqlDataReader reader = null;
public RetrieveText()
{
string strConn = @"server=.\MSSQL2012;integrated security=true;initial catalog=tempdb";
conn = new SqlConnection(strConn);
cmd = new SqlCommand( @"select textfile, textdata from texttable", conn);
conn.Open();
reader = cmd.ExecuteReader();
}
public bool GetRow()
{
long textSize;
int bufferSize = 100;
long charsRead;
textChars = new Char[bufferSize];
if (reader.Read())
{
textFile = reader.GetString(0);
Console.WriteLine( "开始读取文件: " + textFile);
textSize = reader.GetChars(1, 0, null, 0, 0);
Console.WriteLine( "文件大小:{0}个字符" , textSize);
Console.WriteLine( "开始部分的前100个字符:" );
charsRead = reader.GetChars(1, 0, textChars, 0, 100);
Console.WriteLine( new String(textChars));
Console.WriteLine( "最后的100个字符:" );
charsRead = reader.GetChars(1, textSize - 100, textChars, 0, 100);
Console.WriteLine( new String(textChars));
return true;
}
else
{
return false;
}
}
public void endRetrieval()
{
reader.Close();
conn.Close();
}
public static void Main()
{
RetrieveText rt = null;
try
{
rt = new RetrieveText();
while (rt.GetRow() == true)
{
Console.WriteLine( "读取文件结束:" );
Console.WriteLine(rt.textFile);
Console.WriteLine( "" .PadRight(40,'=' ));
}
}
catch (SqlException ex)
{
Console.WriteLine( "出错了:" + ex.ToString());
}
finally
{
rt.endRetrieval();
Console.ReadLine();
}
}
}
}
---------------------------
开始读取文件: .\LoadText.cs
文件大小:3286个字符
开始部分的前100个字符:
// C# ??????м ??????????
// LoadText.cs
using System;
using System.Data;
using System.Data.SqlCli
最后的100个字符:
Bytes has length {0} bytes.", textBytes.Length);
return textBytes;
}
}
}
读取文件结束:
.\LoadText.cs
========================================