
在程序中 最好先初始化一张图片 备用
public void NonePhoto()
{
FileStream fs = new FileStream(Application.StartupPath + "\\\未命名, FileMode.Open, FileAccess.Read);
buffByte = new byte[fs.Length];
fs.Read(buffByte, 0, (int)fs.Length);
fs.Close();
fs = null;
}
然后选择图片的代码
public void PhotoBye()
{
string pathName;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
pathName = openFileDialog1.FileName;
Image im = Image.FromFile(pathName);
pbxPhoto.Image = im;
FileStream fs = new FileStream(pathName, FileMode.Open, FileAccess.Read);
buffByte = new byte[fs.Length];
fs.Read(buffByte, 0, (int)fs.Length);
fs.Close();
fs = null;
}
}
然后插入数据库
insertStr += "stuname,stusex,sturace,telephone,";
insertStr += "photo,classnumber,depno,postalocde,";
insertStr += "role,address,enrolmenttime,classid) values('{0}'";
insertStr += ",'{1}','{2}','{3}','{4}',@photo,'{5}','{6}','{7}','{8}','{9}','{10}','{11}')";
string sqlSrt = string.Format(insertStr, textBox1.Text, txtName.Text, cbxSex.Text, txtRace.Text, txtPhone.Text, CN, DN, txtDakNo.Text, cbxPolitics.Text, txtAddress.Text, dtpEnrollmentTime.Value.Date, CID);
insertDate(sqlSrt);
—————————————————————————————————————————
public void insertDate(string insertSql)
{
SqlConnection conn = BaseClass.databaseconn.dbconnection();
conn.Open();
try
{
SqlCommand insertCmd = new SqlCommand(insertSql, conn);
★ insertCmd.Parameters.Add("@photo", SqlDbType.Image);
★ insertCmd.Parameters["@photo"].Value = buffByte;
int i = insertCmd.ExecuteNonQuery();
if (i > 0)
{
MessageBox.Show("添加学生成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
}
二、
public void showPhoto()
{
SqlConnection conn = BaseClass.databaseconn.dbconnection();
conn.Open();
try
{
SqlCommand cmd = new SqlCommand("select photo from tb_stuinfo where stuno='" + stuNumber + "'", conn);
photoByte = cmd.ExecuteScalar() as byte[];
if (photoByte != null)
{
MemoryStream ms = new MemoryStream(photoByte);
Bitmap bmp = new Bitmap(ms);
this.pictureBox1.Image = bmp;
}
}
