C#把图片添加到数据库

这是一个简单的向数据库中添加图片,显示图片的demo。

Demo中用到的数据库是sqlserver,其中有调用几个操作数据库的静态方法是我从自己写的一个sqlhelp静态类中提取出来的。

这里用到的功能比较少,所以我就没有将sqlhelp类贴出来了,如果有兴趣的朋友可以私信或者留下邮箱我发给你。

由于个人能力有限,难免会有遗漏或者不足之处,欢迎大家批评指正!

以下是具体实现步骤:

打开数据库管理软件sql server management studio 新建一个数据库,取名myPicData,如图:

C#把图片添加到数据库

打开visual studio 新建一个winform应用程序,在设计器中添加三个控件button listbox picturebox

  1. Button控件添加click事件,用来添加图片
  2. Listbox控件添加鼠标点击事件,用来显示数据库中的图片列表,点击列表中的item显示图片
  3. PictureBox控件用来显示图片,设置控件的BackgroundImageLayout属性为ImageLayout.Stretch

如图:

C#把图片添加到数据库
C#把图片添加到数据库

在窗口的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);

}

C#把图片添加到数据库

下面是listbox鼠标点击事件

C#把图片添加到数据库

两个操作数据库的静态方法

C#把图片添加到数据库

获取数据库的所有的表

C#把图片添加到数据库

从数据库中获取数据更新listbox列表

C#把图片添加到数据库

添加图片的方法我就不截图了,贴在后面的所有代码中

完整代码如下:

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());

}

}

}

}

}

}

数据库中数据 如图:

C#把图片添加到数据库


分享到:


相關文章: