我试图遍历表中的每一行并从文件系统更新文件。我不确定这是同时选择和更新的有效方法。如果有更好的方法,请告诉我。
using (SqlConnection oConnection = new SqlConnection(connectionString))
{
oConnection.Open();
using (SqlTransaction oTransaction = oConnection.BeginTransaction())
{
using (SqlCommand oCommand = oConnection.CreateCommand())
{
oCommand.Transaction = oTransaction;
oCommand.CommandType = System.Data.CommandType.Text;
oCommand.CommandText = "SELECT d_id, doc_name, up_date, doc_path FROM Table1 where up_date between '2015/02/03' and '2015/12/30'";
SqlDataReader reader = oCommand.ExecuteReader();
try
{
while (reader.Read())
{
string docPath = string.Format("C:\\{1}", reader["doc_path"].tostring());
int docId = Convert.ToInt32(reader["doc_id"]);
byte[] file;
using (var stream = new FileStream(docPath, FileMode.Open, FileAccess.Read))
{
using (var reader1 = new BinaryReader(stream))
{
file = reader1.ReadBytes((int)stream.Length);
}
}
using (var sqlWrite = new SqlCommand("UPDATE INTO Table1 (doc_file) Values(@File) where doc_id = @docId", connectionString))
{
sqlWrite.Parameters.Add("@File", SqlDbType.VarBinary, file.Length).Value = file;
sqlWrite.Parameters.Add("@docId", SqlDbType.Int32).Value = docId;
sqlWrite.ExecuteNonQuery();
}
}
}
finally
{
// Always call Close when done reading.
reader.Close();
}
}
}
}