SQL Server数据库添加图片读取图片

  1. 下面的代码实现向SQL Server数据库添加图片和文字的功能。
  2. 首先,在SQL查询分析器中执行下面的语句,以创建表和存储过程。
  3. Drop Table Person
  4. Go
  5. Create Table Person
  6. (
  7. PersonID Int Identity,
  8. PersonEmail Varchar(255),
  9. PersonName Varchar(255),
  10. PersonSex Char(1),
  11. PersonDOB DateTime,
  12. PersonImage Image,
  13. PersonImageType Varchar(255)
  14. )
  15. Drop Proc sp_person_isp
  16. Go
  17. Create Proc sp_person_isp
  18. @PersonEmail Varchar(255),
  19. @PersonName Varchar(255),
  20. @PersonSex Char(1),
  21. @PersonDOB DateTime,
  22. @PersonImage Image,
  23. @PersonImageType Varchar(255)
  24. As
  25. Begin
  26.   Insert into Person 
  27.    (PersonEmail, PersonName, PersonSex, 
  28.    PersonDOB, PersonImage, PersonImageType)
  29.    Values
  30.    (@PersonEmail, @PersonName, @PersonSex, 
  31.    @PersonDOB, @PersonImage, @PersonImageType)
  32. End
  33. Go
  34. 下面就是完整的代码,拷贝即可运行:
  35. <%@ Import Namespace="System.IO" %>
  36. <%@ Import Namespace="System.Data.SqlClient" %>
  37. <%@ Import Namespace="System.Data" %>
  38. <%@ Page Language="vb" %>
  39. <HTML>
  40. <HEAD>
  41. <title>向SQL Server插入图片</title>
  42. <script runat="server">
  43. Public Sub AddPerson(sender As Object, e As EventArgs)
  44.   Dim intImageSize As Int64
  45.   Dim strImageType As String
  46.   Dim ImageStream As Stream
  47.   ' 获得图片的大小
  48.   intImageSize = PersonImage.PostedFile.ContentLength
  49.   ' 获得图片类型
  50.   strImageType = PersonImage.PostedFile.ContentType
  51.   '读取图片
  52.   ImageStream = PersonImage.PostedFile.InputStream
  53.   Dim ImageContent(intImageSize) As Byte
  54.   Dim intStatus As Integer
  55.   intStatus = ImageStream.Read(ImageContent, 0, intImageSize)
  56.   ' 创建Connection和Command对象
  57.   Dim strCnn As String = "Data Source=.;Initial Catalog=mxh;User Id=sa;Password=;"
  58.   Dim myConnection As New SqlConnection(strCnn)
  59.   Dim myCommand As New SqlCommand("sp_person_isp", myConnection)
  60.   ' 使用存储过程
  61.   myCommand.CommandType = CommandType.StoredProcedure
  62.   ' 向存储过程添加参数
  63.   Dim prmEmail As New SqlParameter("@PersonEmail", SqlDbType.VarChar, 255)
  64.   prmEmail.Value = txtPersonEmail.Text
  65.   myCommand.Parameters.Add(prmEmail)
  66.   Dim prmName As New SqlParameter("@PersonName", SqlDbType.VarChar, 255)
  67.   prmName.Value = txtPersonName.Text
  68.   myCommand.Parameters.Add(prmName)
  69.   Dim prmSex As New SqlParameter("@PersonSex", SqlDbType.Char, 1)
  70.   If sexMale.Checked Then
  71.       prmSex.Value = "M"
  72.   Else
  73.       prmSex.Value = "F"
  74.   End If
  75.   myCommand.Parameters.Add(prmSex)
  76.   
  77.   Dim prmPersonDOB As New SqlParameter("@PersonDOB", SqlDbType.DateTime)
  78.   prmPersonDOB.Value = txtPersonDob.Text
  79.   myCommand.Parameters.Add(prmPersonDOB)
  80.   Dim prmPersonImage As New SqlParameter("@PersonImage", SqlDbType.Image)
  81.   prmPersonImage.Value = ImageContent
  82.   myCommand.Parameters.Add(prmPersonImage)
  83.   Dim prmPersonImageType As New SqlParameter("@PersonImageType", SqlDbType.VarChar, 255)
  84.   prmPersonImageType.Value = strImageType
  85.   myCommand.Parameters.Add(prmPersonImageType)
  86.   Try
  87.       myConnection.Open()
  88.       myCommand.ExecuteNonQuery()
  89.       myConnection.Close()
  90.       Response.Write("添加成功!")
  91.     Catch SQLexc As SqlException
  92.     Response.Write("添加失败,原因:" & SQLexc.ToString())
  93.   End Try
  94. End Sub
  95. </script>
  96. </HEAD>
  97. <body style="FONT: 9pt 宋体">
  98.     <form enctype="multipart/form-data" runat="server" ID="Form1">
  99.       <asp:Table Runat="server" Width="50%" BorderWidth="1" BackColor="Beige" ID="Table1"
  100.      Font-Name="宋体" Font-Size="9pt">
  101.         <asp:TableRow>
  102.           <asp:TableCell ColumnSpan="2" BackColor="#ff0000">
  103.             <asp:Label ForeColor="#ffffff" font-bold="True" Runat="server" Text="添加新用户" ID="Label1" />
  104.           </asp:TableCell>
  105.         </asp:TableRow>
  106.         <asp:TableRow>
  107.           <asp:TableCell HorizontalAlign="Right">
  108.             <asp:Label Runat="server" Text="姓名" ID="Label2" />
  109.           </asp:TableCell>
  110.           <asp:TableCell>
  111.             <asp:TextBox id="txtPersonName" Runat="server" />
  112.           </asp:TableCell>
  113.         </asp:TableRow>
  114.         <asp:TableRow>
  115.           <asp:TableCell HorizontalAlign="Right">
  116.             <asp:Label Runat="server" Text="电子邮件" ID="Label3" />
  117.           </asp:TableCell>
  118.           <asp:TableCell>
  119.             <asp:TextBox id="txtPersonEmail" Runat="server" />
  120.           </asp:TableCell>
  121.         </asp:TableRow>
  122.         <asp:TableRow>
  123.           <asp:TableCell HorizontalAlign="Right">
  124.             <asp:Label Runat="server" Text="性别" ID="Label4"/>
  125.           </asp:TableCell>
  126.           <asp:TableCell>
  127.             <asp:RadioButton GroupName="sex"  Text="男" ID="sexMale" Runat="server" />
  128.             <asp:RadioButton GroupName="sex"  Text="女" ID="sexFeMale" Runat="server" />
  129.           </asp:TableCell>
  130.         </asp:TableRow>
  131.         <asp:TableRow>
  132.           <asp:TableCell HorizontalAlign="Right">
  133.             <asp:Label Runat="server" Text="出生日期" ID="Label5"/>
  134.           </asp:TableCell>
  135.           <asp:TableCell>
  136.             <asp:TextBox id="txtPersonDOB" Runat="server" />
  137.           </asp:TableCell>
  138.         </asp:TableRow>
  139.         <asp:TableRow>
  140.           <asp:TableCell HorizontalAlign="Right">
  141.             <asp:Label Runat="server" Text="照片" ID="Label6"/>
  142.           </asp:TableCell>
  143.           <asp:TableCell>
  144.             <input type="file" id="PersonImage" runat="server" NAME="PersonImage" /></asp:TableCell>
  145.         </asp:TableRow>
  146.         <asp:TableRow>
  147.           <asp:TableCell ColumnSpan="2" HorizontalAlign="Center">
  148.             <asp:Button Text=" 添  加 " OnClick="AddPerson" Runat="server" ID="Button1"/>
  149.           </asp:TableCell>
  150.         </asp:TableRow>
  151.       </asp:Table>
  152.     </form>
  153. </body>
  154. </HTML>

 

================================================================================

  1. 下面的代码实现从SQL Server数据库提取图片并显示在DataGrid的功能。
  2. 下面就是完整的代码,拷贝即可运行:
  3. <%@ Page Language="vb" %>
  4. <%@ Import Namespace="System.Data" %>
  5. <%@ Import Namespace="System.Data.SqlClient" %>
  6. <html>
  7. <head>
  8. <title>用户列表</title>
  9. <script runat=server>
  10. Sub Page_Load(sender As Object, e As EventArgs)
  11.   If Not Page.IsPostBack Then
  12.   BindGrid()
  13.   End If
  14. End Sub
  15. Private Sub BindGrid()
  16.   Dim strCnn As String = "Data Source=.;Initial Catalog=mxh;User Id=sa;Password=;"
  17.   Dim myConnection As SqlConnection = New SqlConnection(strCnn)
  18.   Dim myCommand As SqlCommand = New SqlCommand("SELECT * FROM Person", myConnection)
  19.   myCommand.CommandType = CommandType.Text
  20.   Try
  21.     myConnection.Open()
  22.     DG_Persons.DataSource = myCommand.ExecuteReader(CommandBehavior.CloseConnection)
  23.     DG_Persons.DataBind()
  24.     Catch SQLexc As SqlException
  25.     Response.Write("Error occured while Generating Data. Error is " & SQLexc.ToString())
  26.   End Try
  27. End Sub
  28. Function FormatURL(strArgument) as String
  29.   Return ("ReadImage.aspx?id=" & strArgument)
  30. End Function
  31. </script>
  32. </head>
  33. <body style="font: 9pt 宋体">
  34. <h3 align=center>从数据库中取得照片并显示在DataGrid中</h3>
  35. <form id="Form1" method="post" runat="server">
  36. <asp:DataGrid ID="DG_Persons" AutoGenerateColumns=False Width="99%"
  37.  HeaderStyle-BackColor="#ff0000" HeaderStyle-Font-Bold="True" HeaderStyle-ForeColor="#ffffff"
  38.  ItemStyle-BackColor=Beige BorderColor="#000000" Runat=server HeaderStyle-HorizontalAlign=Center>
  39. <Columns>
  40. <asp:TemplateColumn HeaderText="姓名">
  41. <ItemTemplate>
  42. <asp:Label Runat="server"  Text='<%# DataBinder.Eval(Container.DataItem, "PersonName") %>' ID="Label1"/>
  43. </ItemTemplate>                               
  44. </asp:TemplateColumn>
  45. <asp:TemplateColumn HeaderText="电子邮件">
  46. <ItemTemplate>
  47. <asp:Label Runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "PersonEmail") %>' ID="Label2"/>
  48. </ItemTemplate>                               
  49. </asp:TemplateColumn>
  50. <asp:TemplateColumn HeaderText="性别">
  51. <ItemTemplate>
  52. <asp:Label Runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "PersonSex") %>' ID="Label3"/>
  53. </ItemTemplate>                               
  54. </asp:TemplateColumn>
  55. <asp:TemplateColumn HeaderText="出生日期">
  56. <ItemTemplate>
  57. <asp:Label Runat="server" 
  58.   Text='<%# DataBinder.Eval(Container.DataItem, "PersonDOB") %>' ID="Label4"/>
  59. </ItemTemplate>                               
  60. </asp:TemplateColumn>
  61. <asp:TemplateColumn HeaderText="照片">
  62. <ItemTemplate>
  63. <asp:Image Runat=server ID="Image1"  Width="150" Height="125"
  64.  ImageUrl='<%# FormatURL(DataBinder.Eval(Container.DataItem, "PersonID")) %>'  />
  65. </ItemTemplate>                               
  66. </asp:TemplateColumn>
  67. </Columns>
  68. </asp:DataGrid>
  69. </form>
  70. </body>
  71. </html>
  72. ReadImage.aspx
  73. <%@ Page Language="vb" %>
  74. <%@ Import Namespace="System.Data" %>
  75. <%@ Import Namespace="System.Data.SqlClient" %>
  76. <HTML>
  77. <HEAD>
  78. <script runat=server>
  79. Public Sub Page_Load(sender As Object, e As EventArgs)
  80.   Dim strImageID as String = Request.QueryString("id")
  81.   Dim myConnection As New SqlConnection("Data Source=.;Initial Catalog=mxh;User Id=sa;Password=;")
  82.   Dim myCommand As New SqlCommand("Select PersonImageType, PersonImage from Person Where PersonID=" _
  83.     + strImageID, myConnection)
  84.   Try
  85.     myConnection.Open()
  86.     Dim myDataReader as SqlDataReader 
  87.     myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection)
  88.     Do While (myDataReader.Read())
  89.     Response.ContentType = myDataReader.Item("PersonImageType")
  90.     Response.BinaryWrite(myDataReader.Item("PersonImage"))
  91.     Loop
  92.     myConnection.Close()
  93.     Catch SQLexc As SqlException
  94.   End Try
  95. End Sub    
  96. </script>
  97. </HEAD>
  98. <body>
  99. <form runat="server" ID="Form1"></form>
  100. </body>
  101. </HTML>
  102. C# 版本
  103. DataGridShowImage.aspx
  104. <%@ Page language="c#" debug="true" Codebehind="DataGridShowImage.aspx.cs" AutoEventWireup="false"
  105.  Inherits="eMeng.Exam.DataGridShowImage.DataGridShowImage" %>
  106. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
  107. <HTML>
  108. <HEAD>
  109.   <title>从数据库中取得照片并显示在DataGrid中</title>
  110.   <meta name="GENERATOR" Content="Microsoft Visual Studio 7.0">
  111.   <meta name="CODE_LANGUAGE" Content="C#">
  112.   <meta name="vs_defaultClientScript" content="JavaScript">
  113.   <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
  114. </HEAD>
  115. <body MS_POSITIONING="GridLayout">
  116. <form id="DataGridShowImage" method="post" runat="server">
  117.   <h3 align="center">从数据库中取得照片并显示在DataGrid中</h3>
  118.   <asp:DataGrid ID="DG_Persons" AutoGenerateColumns="False" Width="99%" HeaderStyle-BackColor="#ff0000"
  119.    HeaderStyle-Font-Bold="True" HeaderStyle-ForeColor="#ffffff" ItemStyle-BackColor="Beige"
  120.     BorderColor="#000000" Runat="server" HeaderStyle-HorizontalAlign="Center">
  121.   <Columns>
  122.     <asp:TemplateColumn HeaderText="姓名">
  123.       <ItemTemplate>
  124.         <asp:Label Runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "PersonName") %>' ID="Label1"/>
  125.       </ItemTemplate>
  126.     </asp:TemplateColumn>
  127.     <asp:TemplateColumn HeaderText="电子邮件">
  128.       <ItemTemplate>
  129.         <asp:Label Runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "PersonEmail") %>' ID="Label2"/>
  130.       </ItemTemplate>
  131.     </asp:TemplateColumn>
  132.     <asp:TemplateColumn HeaderText="性别">
  133.       <ItemTemplate>
  134.         <asp:Label Runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "PersonSex") %>' ID="Label3"/>
  135.       </ItemTemplate>
  136.     </asp:TemplateColumn>
  137.     <asp:TemplateColumn HeaderText="出生日期">
  138.       <ItemTemplate>
  139.         <asp:Label Runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "PersonDOB") %>' ID="Label4"/>
  140.       </ItemTemplate>
  141.     </asp:TemplateColumn>
  142.     <asp:TemplateColumn HeaderText="照片">
  143.       <ItemTemplate>
  144.         <asp:Image Runat=server ID="Image1"
  145.          ImageUrl='<%# FormatURL(DataBinder.Eval(Container.DataItem, "PersonID")) %>' />
  146.       </ItemTemplate>
  147.     </asp:TemplateColumn>
  148.   </Columns>
  149.   </asp:DataGrid>
  150. </form>
  151. </body>
  152. </HTML>
  153. DataGridShowImage.aspx.cs
  154. using System;
  155. using System.Collections;
  156. using System.ComponentModel;
  157. using System.Data;
  158. using System.Drawing;
  159. using System.Web;
  160. using System.Web.SessionState;
  161. using System.Web.UI;
  162. using System.Web.UI.WebControls;
  163. using System.Web.UI.HtmlControls;
  164. using System.Data.SqlClient;
  165. namespace eMeng.Exam.DataGridShowImage
  166. {
  167.  /// <summary>
  168.  /// DataGridShowImage 的摘要说明。
  169.  /// </summary>
  170.  public class DataGridShowImage : System.Web.UI.Page
  171.  {
  172.   protected System.Web.UI.WebControls.DataGrid DG_Persons;
  173.   private void Page_Load(object sender, System.EventArgs e)
  174.   {
  175.    // 在此处放置用户代码以初始化页面
  176.    if(!this.IsPostBack)
  177.    {
  178.     BindGrid();
  179.    }
  180.   }
  181.   private void BindGrid()
  182.   {
  183.    string strCnn  = "Data Source=.;Initial Catalog=mxh;User Id=sa;Password=;";
  184.    SqlConnection myConnection = new SqlConnection(strCnn);
  185.    SqlCommand myCommand = new SqlCommand("SELECT * FROM Person", myConnection);
  186.    myCommand.CommandType = CommandType.Text;
  187.    try
  188.    {
  189.     myConnection.Open();
  190.     DG_Persons.DataSource = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
  191.     DG_Persons.DataBind();
  192.    }
  193.    catch(SqlException SQLexc)
  194.    {
  195.     Response.Write("提取数据时出现错误:" + SQLexc.ToString());
  196.    }
  197.   }
  198.   protected string FormatURL(object strArgument)
  199.   {
  200.    return "ReadImage.aspx?id=" + strArgument.ToString();
  201.   }
  202. #region Web Form Designer generated code
  203.   override protected void OnInit(EventArgs e)
  204.   {
  205.    //
  206.    // CODEGEN:该调用是 ASP.NET Web 窗体设计器所必需的。
  207.    //
  208.    InitializeComponent();
  209.    base.OnInit(e);
  210.   }
  211.   /// <summary>
  212.   /// 设计器支持所需的方法 - 不要使用代码编辑器修改
  213.   /// 此方法的内容。
  214.   /// </summary>
  215.   private void InitializeComponent()
  216.   {    
  217.    this.Load += new System.EventHandler(this.Page_Load);
  218.   }
  219. #endregion
  220.  }
  221. }
  222. ReadImage.aspx
  223. <%@ Page language="c#" Codebehind="ReadImage.aspx.cs" AutoEventWireup="false"
  224.  Inherits="eMeng.Exam.DataGridShowImage.ReadImage" %>
  225. ReadImage.aspx.cs
  226. using System;
  227. using System.Collections;
  228. using System.ComponentModel;
  229. using System.Data;
  230. using System.Drawing;
  231. using System.Web;
  232. using System.Data.SqlClient;
  233. using System.Web.SessionState;
  234. using System.Web.UI;
  235. using System.Web.UI.WebControls;
  236. using System.Web.UI.HtmlControls;
  237. namespace eMeng.Exam.DataGridShowImage
  238. {
  239.   /// <summary>
  240.   /// ReadImage 的摘要说明。
  241.   /// </summary>
  242.   public class ReadImage : System.Web.UI.Page
  243.   {
  244.   private void Page_Load(object sender, System.EventArgs e)
  245.   {
  246.    // 在此处放置用户代码以初始化页面
  247.    string strImageID = Request.QueryString["id"];
  248.    SqlConnection myConnection = new SqlConnection("Data Source=.;Initial Catalog=mxh;User Id=sa;Password=;");
  249.    SqlCommand myCommand = new SqlCommand("Select PersonImageType, PersonImage from Person Where PersonID=" 
  250.     + strImageID, myConnection);
  251.    try
  252.    {
  253.     myConnection.Open();
  254.     SqlDataReader myDataReader;
  255.     myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
  256.     if(myDataReader.Read())
  257.     {
  258.      Response.Clear();
  259.      Response.ContentType = myDataReader["PersonImageType"].ToString();
  260.      Response.BinaryWrite((byte[])myDataReader["PersonImage"]);
  261.     }
  262.     myConnection.Close();
  263.    }
  264.    catch (SqlException SQLexc)
  265.    {
  266.    }
  267.    Response.End();
  268.   }
  269.     #region Web Form Designer generated code
  270.     override protected void OnInit(EventArgs e)
  271.     {
  272.       //
  273.       // CODEGEN:该调用是 ASP.NET Web 窗体设计器所必需的。
  274.       //
  275.       InitializeComponent();
  276.       base.OnInit(e);
  277.     }
  278.         
  279.     /// <summary>
  280.     /// 设计器支持所需的方法 - 不要使用代码编辑器修改
  281.     /// 此方法的内容。
  282.     /// </summary>
  283.     private void InitializeComponent()
  284.     {    
  285.       this.Load += new System.EventHandler(this.Page_Load);
  286.     }
  287.     #endregion
  288.   }
  289. }

=======================================================================

转贴地址:

向数据库中保存图片:
http://dotnet.aspx.cc/article/2a5dd7c6-a45a-48ab-a2e8-342a29f17506/read.aspx
从SQL Server数据库提取图片并显示在DataGrid:
http://dotnet.aspx.cc/article/ecd9ae16-8ff0-4a1c-9b9f-5e8b641cb1b1/read.aspx

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值