向数据库中保存不同类型的文件,和在数据库中保存图片是一样的。就是向数据库以byte形式存入
向数据库中保存不同类型的文件,和在数据库中保存图片是一样的。就是向数据库以byte形式存入
然后就是写入数据库,代码如下:
FileInfo fi = new FileInfo( txtFileName.Text )// Replace with your file name
if ( fi.Exists
{
byte[] bData = null
int nNewFileID = 0
// Read file data into buffer
using ( FileStream fs = fi.OpenRead() )
{
bData = new byte[fi.Length]
int nReadLength = fs.Read( bData,0, (int)(fi.Length) )
}
// Add file info into DB
string strQuery = "INSERT INTO FileInfo "
+ " ( FileName, FullName, FileData ) "
+ " VALUES "
+ " ( @FileName, @FullName, @FileData ) "
+ " SELECT @@IDENTITY AS 'Identity'"
SqlCommand sqlComm = new SqlCommand( strQuery, sqlConn )
sqlComm.Parameters.Add( "@FileName", fi.Name )
sqlComm.Parameters.Add( "@FullName", fi.FullName )
sqlComm.Parameters.Add( "@FileData", bData )
// Get new file ID
SqlDataReader sqlReader = sqlComm.ExecuteReader()
if( sqlReader.Read() )
{
nNewFileID = int.Parse(sqlReader.GetValue(0).ToString())
}
sqlReader.Close()
sqlComm.Dispose()
if( nNewFileID >0 )
{
// Add new item in list view
ListViewItem itmNew = lsvFileInfo.Items.Add( fi.Name )
itmNew.Tag = nNewFileID
}
}
4.而读出的代码如下:
// Get new file name
string strFullName =
dlgFBSave.SelectedPath
if( strFullName[strFullName.Length - 1] != '//'
)
strFullName
+= @"/"
strFullName +=
lsvFileInfo.SelectedItems[0].Text
string strQuery = "SELECT FileData FROM FileInfo
"
+
" WHERE FileID = " + lsvFileInfo.SelectedItems[0].Tag.ToString()
SqlDataAdapter
sqlDAdapter = new SqlDataAdapter(strQuery,sqlConn)
DataSet
sqlRecordSet = new DataSet()
byte[] bData = null
//Get file data from DB
try
{
sqlDAdapter.Fill(
sqlRecordSet, "FileInfo" )
foreach( DataRow dr in sqlRecordSet.Tables["FileInfo"].Rows)
{
if( dr["FileData"] != DBNull.Value )
bData
= ( byte[] )dr["FileData"]
}
}
catch(SqlException sqlErr)
{
MessageBox.Show(
sqlErr.Message )
}
catch
{
MessageBox.Show(
"Failed to read data from DB!" )
}
sqlRecordSet.Dispose()
sqlDAdapter.Dispose()
if( bData != null )
{
// Save file
FileInfo
fi = new FileInfo( strFullName
)
if( !fi.Exists )
{
//Create the file.
using (FileStream fs = fi.Create())
{
fs.Write(
bData, 0, bData.Length)
}
}
else
{
//Create the file.
using (FileStream fs =
fi.OpenWrite())
{
fs.Write(
bData, 0, bData.Length)
}
}
}
1、用SQL SERVER的话,用TEXT数据类型,可以存2,147,483,647个字符,足够存放很长的文章了。
2、如果是Oracle数据库的话,可以用clob字段类型。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)