SqlParameter 操作 image 字段
public static void AddEmployee( string lastName, string firstName, string title, DateTime hireDate, int reportsTo, string photoFilePath, string connectionString) { byte[] photo = GetPhoto(photoFilePath); using (SqlConnection connection = new SqlConnection( connectionString)) SqlCommand command = new SqlCommand( "INSERT INTO Employees (LastName, FirstName, " + "Title, HireDate, ReportsTo, Photo) " + "Values(@LastName, @FirstName, @Title, " + "@HireDate, @ReportsTo, @Photo)", connection); command.Parameters.Add("@LastName", SqlDbType.NVarChar, 20).Value = lastName; command.Parameters.Add("@FirstName", SqlDbType.NVarChar, 10).Value = firstName; command.Parameters.Add("@Title", SqlDbType.NVarChar, 30).Value = title; command.Parameters.Add("@HireDate", SqlDbType.DateTime).Value = hireDate; command.Parameters.Add("@ReportsTo", SqlDbType.Int).Value = reportsTo; command.Parameters.Add("@Photo", SqlDbType.Image, photo.Length).Value = photo; connection.Open(); command.ExecuteNonQuery(); } } public static byte[] GetPhoto(string filePath) { FileStream stream = new FileStream( filePath, FileMode.Open, FileAccess.Read); BinaryReader reader = new BinaryReader(stream); byte[] photo = reader.ReadBytes((int)stream.Length); reader.Close(); stream.Close(); return photo; }
from: https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/sql/inserting-an-image-from-a-file
posted on 2019-03-08 14:19 wangzhiliang 阅读(184) 评论(0) 编辑 收藏 举报