存图片到数据库
Q:存图片到数据库
A:using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;
using System.IO;
namespace CExample
{
public class ImageDB : System.Windows.Forms.Form
{
private System.Windows.Forms.Button BtnAdd;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox EdtID;
private System.Windows.Forms.TextBox EdtImage;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Button BtnShow;
private System.Windows.Forms.PictureBox StudentPhoto;
...
private void BtnAdd_Click(object sender, System.EventArgs e)
{
AddStudentPhoto(102, @"C:\Temp\1.jpg");
}
private void AddStudentPhoto(int Student_ID, string ImageFile)
{
FileStream myFile = new FileStream(ImageFile, FileMode.Open, FileAccess.Read);
byte[] Photo = new byte[myFile.Length];
myFile.Read(Photo, 0, (int)myFile.Length);
myFile.Close();
SavePhotoToDB(Student_ID, Photo);
}
private void SavePhotoToDB(int Student_ID, byte[] Photo)
{
string ConnectString = "data source=Hellcat;initial catalog=SMS;" +
"User ID=***;password=***";
using (SqlConnection myCon = new SqlConnection(ConnectString) )
{
if (myCon.State != ConnectionState.Open) //if connection is not open, open it
myCon.Open();
SqlCommand myCmd = new SqlCommand("AddStudentPhoto", myCon);
myCmd.CommandType = CommandType.StoredProcedure;
myCmd.Parameters.Add(new SqlParameter("@Student_ID", SqlDbType.Int, 0));
myCmd.Parameters.Add(new SqlParameter("@Photo", SqlDbType.Image));
myCmd.Parameters["@Student_ID"].Value = Student_ID;
myCmd.Parameters["@Photo"].Value = Photo;
myCmd.ExecuteNonQuery();
myCon.Close();
MessageBox.Show("Add student photo successfully!");
}
}
}
}