• 把图片存入数据库


    图片存入数据库需要把图片转成二进制才能存入,怎么把图片转成二进制,这就是关键。

    首先,在sql数据库建一个表image,只有一个字段im,数据类型image。

    建好之后,打开visual studio,建一个windows窗体应用程序

    下面是效果图:

    代码:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.IO;
    using System.Data.SqlClient;
    
    namespace TestForm1
    {
        public partial class FormImageInSql : Form
        {
            public FormImageInSql()
            {
                InitializeComponent();
            }
    
           /// <summary>
            /// 存入数据库
           /// </summary>
            private void btn_before_Click(object sender, EventArgs e)
            {
                string filePath = @"....Imagesqiaoba.jpg";//WinForm窗体项目起始在debug文件夹下,写路径的时候注意了
                FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                byte[] buffer = new byte[fs.Length];
                fs.Read(buffer, 0, (int)fs.Length);
                SqlConnection con = DBHelper.getConnection();
                string cmd_str = "insert into Image values(@buffer)";
                SqlCommand cmd = new SqlCommand(cmd_str, con);
                SqlParameter para = new SqlParameter("@buffer", SqlDbType.Image);
                para.Value = buffer;
                cmd.Parameters.Add(para);
                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();
                MessageBox.Show("存入成功!");
            }
    
            /// <summary>
            /// 从数据库中读出
            /// </summary>
            private void btn_after_Click(object sender, EventArgs e)
            {
                string con_str = "select top 1 im from Image ";
                SqlConnection con = DBHelper.getConnection();
                SqlCommand cmd = new SqlCommand(con_str, con); con.Open();
                SqlDataReader dr = cmd.ExecuteReader();
                dr.Read();
                MemoryStream ms = new MemoryStream((byte[])dr["im"]);
                Image image = Image.FromStream(ms, true);
                dr.Close();
                con.Close();
                pb_after.SizeMode = PictureBoxSizeMode.StretchImage;
                pb_after.Image = image; 
            }
        }
    }
    
  • 相关阅读:
    监听器
    过滤器
    连接池与分页
    jdbc优化
    jdbc入门
    web开发mysql基础
    自定义标签
    jsp基础
    会话管理入门
    19. Remove Nth Node From End of List C++删除链表的倒数第N个节点
  • 原文地址:https://www.cnblogs.com/xushining/p/3186100.html
Copyright © 2020-2023  润新知