這是一個簡單的向數據庫中添加圖片,顯示圖片的demo。
Demo中用到的數據庫是sqlserver,其中有調用幾個操作數據庫的靜態方法是我從自己寫的一個sqlhelp靜態類中提取出來的。
這裡用到的功能比較少,所以我就沒有將sqlhelp類貼出來了,如果有興趣的朋友可以私信或者留下郵箱我發給你。
由於個人能力有限,難免會有遺漏或者不足之處,歡迎大家批評指正!
以下是具體實現步驟:
打開數據庫管理軟件sql server management studio 新建一個數據庫,取名myPicData,如圖:
打開visual studio 新建一個winform應用程序,在設計器中添加三個控件button listbox picturebox
- Button控件添加click事件,用來添加圖片
- Listbox控件添加鼠標點擊事件,用來顯示數據庫中的圖片列表,點擊列表中的item顯示圖片
- PictureBox控件用來顯示圖片,設置控件的BackgroundImageLayout屬性為ImageLayout.Stretch
如圖:
在窗口的load事件中判斷數據庫中是否有保存圖片的表,如果沒有則新建一個
//在數據庫中新建一個pic_Table表用來保存添加的圖片
string sql = @"CREATE TABLE pic_Table
(ID int NOT NULL IDENTITY(1,1) PRIMARY KEY, name nvarchar(50) NOT NULL, picture image NOT NULL, date datetime NOT NULL )";
//獲取當前數據庫中所有表
List<string> tableList = new List<string>();/<string>/<string>
GetTableInDatabase(tableList);
//判斷pic_Table表(庫存表)是否存在 沒有則創建
if (!tableList.Contains("pic_Table"))
{
ExecuteNonQuery(sql);
}
下面是listbox鼠標點擊事件
兩個操作數據庫的靜態方法
獲取數據庫的所有的表
從數據庫中獲取數據更新listbox列表
添加圖片的方法我就不截圖了,貼在後面的所有代碼中
完整代碼如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace 圖片添加到數據庫
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//連接數據庫
private static readonly string constr = "server=19.41.238.68;database=myPicData;uid=sa;pwd=xia123456";
private void Form1_Load(object sender, EventArgs e)
{
//在數據庫中新建一個pic_Table表用來保存添加的圖片
string sql = @"CREATE TABLE pic_Table
(ID int NOT NULL IDENTITY(1,1) PRIMARY KEY, name nvarchar(50) NOT NULL, picture image NOT NULL, date datetime NOT NULL )";
//獲取當前數據庫中所有表
List<string> tableList = new List<string>();/<string>/<string>
GetTableInDatabase(tableList);
//判斷pic_Table是否存在 沒有則創建
if (!tableList.Contains("pic_Table"))
{
ExecuteNonQuery(sql);
}
//將pictureBox控件的背景圖片佈局屬性設置為平鋪
this.pictureBox1.BackgroundImageLayout = ImageLayout.Stretch;
//給listbox控件添加鼠標單擊事件
this.listPic.MouseClick += listPic_MouseClick;
//從數據庫中加載圖片信息列表在listbox中
UpdatePicNameList();
}
//鼠標單擊顯示圖片信息
void listPic_MouseClick(object sender, MouseEventArgs e)
{
if (listPic.SelectedIndex >= 0)
{
string sqlstr = "select * from [dbo].[pic_Table] where name = @picName";
SqlParameter par = new SqlParameter("@picName", SqlDbType.NVarChar, 50) { Value = listPic.SelectedItem.ToString().Trim() };
using (SqlDataReader reader = ExecuteReader(sqlstr, par))
{
if (reader.HasRows)
{
while (reader.Read())
{
byte[] bytes = (byte[])reader["picture"];
using (MemoryStream stream = new MemoryStream(bytes))
{
pictureBox1.BackgroundImage = Image.FromStream(stream);
}
}
}
}
}
}
/// <summary>
/// 執行增 刪 改 的方法
///
/// <param>
/// <param>
/// <returns>
public static int ExecuteNonQuery(string sql, params SqlParameter[] pms)
{
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(sql, con))
{
if (pms != null)
{
cmd.Parameters.AddRange(pms);
}
con.Open();
return cmd.ExecuteNonQuery();
}
}
}
/// <summary>
/// 返回多個值的方法
///
/// <param>
/// <param>
/// <returns>
public static SqlDataReader ExecuteReader(string sql, params SqlParameter[] pms)
{
SqlConnection con = new SqlConnection(constr);
using (SqlCommand cmd = new SqlCommand(sql, con))
{
if (pms != null)
{
cmd.Parameters.AddRange(pms);
}
try
{
con.Open();
//System.Data.CommandBehavior.CloseConnection這個枚舉表示將來使用完畢SqlDataReader之後
//在關閉reader的同時,也會關閉con連接
return cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
}
catch
{
con.Close();
con.Dispose();
throw;
}
}
}
/// <summary>
/// 獲取當前數據庫中所有表
///
/// <param>
public static void GetTableInDatabase(List<string> tableList)/<string>
{
string sql = "SELECT OBJECT_NAME(id) FROM sysobjects WHERE xtype = 'U' AND OBJECTPROPERTY(id,'IsMSShipped')=0";
try
{
using (SqlDataReader reader = ExecuteReader(sql))
{
if (reader.HasRows)
{
while (reader.Read())
{
tableList.Add(reader.GetString(0));
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
//添加圖片
private void btnAddPic_Click(object sender, EventArgs e)
{
OpenFileDialog openfile = new OpenFileDialog();
openfile.Title = "選擇一張不超過2MB的設備圖片";
openfile.Filter = "高質量圖片文件(*.jpg *.bmp *.png)|*.jpg;*.bmp;*.png";
openfile.FilterIndex = 1;
openfile.RestoreDirectory = true;
if (openfile.ShowDialog() == DialogResult.OK)
{
try
{
string picPath = openfile.FileName;
using (FileStream stream = new FileStream(picPath, FileMode.Open, FileAccess.Read))
{
//判斷圖片大小是否超過2MB
byte[] bytes = new byte[stream.Length];
if (bytes.Length > 1024 * 1024 * 2)
{
MessageBox.Show("圖片超過設定的大小,請選擇一張小於2MB的圖片。");
}
else
{
#region
//打開圖片
stream.Read(bytes, 0, bytes.Length);
pictureBox1.BackgroundImage = Image.FromFile(picPath);
//在數據庫中查找圖片名 判斷是否存在同名圖片
string sqlQuery = "select * from [dbo].[pic_Table] where name = @picName";
SqlParameter par = new SqlParameter("@picName", SqlDbType.NVarChar) { Value = Path.GetFileName(picPath) };
using (SqlDataReader reader = ExecuteReader(sqlQuery, par))
{
if (reader.HasRows)
{
//數據庫中存在同名圖片 進行更新處理
DialogResult result = MessageBox.Show("數據庫中已經存在名稱為: " + Path.GetFileName(picPath) + " 的圖片,如果需要更新圖片請選擇'Yes',退出請選擇'取消'",
"提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (result == System.Windows.Forms.DialogResult.Yes)
{
string sqlUpdate = "update [dbo].[pic_Table] set ( picture = @picBytes, date=@nowDate ) where name =@picName";
SqlParameter[] pars = new SqlParameter[]{
new SqlParameter("@picBytes", SqlDbType.Image ) { Value = bytes },
new SqlParameter("@picName", SqlDbType.NVarChar, 50 ){ Value = Path.GetFileName(picPath) },
new SqlParameter("@nowDate",SqlDbType.DateTime) { Value = DateTime.Now.ToString() }
};
ExecuteNonQuery(sqlUpdate, pars);
}
else
{
return;
}
}
else
{
//數據庫中沒有同名圖片 插入新的數據
string sqlInsert = "insert into [dbo].[pic_Table] (name, picture , date) Values (@picName,@picBytes,@nowDate)";
SqlParameter[] pars = new SqlParameter[]{
new SqlParameter("@picName", SqlDbType.NVarChar, 50 ){ Value = Path.GetFileName(picPath) },
new SqlParameter("@picBytes", SqlDbType.Image ) { Value = bytes },
new SqlParameter("@nowDate",SqlDbType.DateTime) { Value = DateTime.Now.ToString()}
};
ExecuteNonQuery(sqlInsert, pars);
}
}
#endregion
}
}
MessageBox.Show("添加成功!");
UpdatePicNameList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
/// <summary>
/// 更新圖片名稱列表
///
private void UpdatePicNameList()
{
listPic.Items.Clear();
string sqlstr = "select name from [dbo].[pic_Table]";
using (SqlDataReader reader = ExecuteReader(sqlstr))
{
if (reader.HasRows)
{
while (reader.Read())
{
listPic.Items.Add(reader["name"].ToString());
}
}
}
}
}
}
數據庫中數據 如圖:
閱讀更多 路馬編程 的文章