向SQL Server數據庫添加圖片和文字的功能

下面的代碼實現向SQL Server數據庫添加圖片和文字的功能。

首先,在SQL查詢分析器中執行下面的語句,以創建表和存儲過程。

Drop Table Person Go Create Table Person ( PersonID Int Identity, PersonEmail Varchar(255), PersonName Varchar(255), PersonSex Char(1), PersonDOB DateTime, PersonImage Image, PersonImageType Varchar(255) ) Drop Proc sp_person_isp Go Create Proc sp_person_isp @PersonEmail Varchar(255), @PersonName Varchar(255), @PersonSex Char(1), @PersonDOB DateTime, @PersonImage Image, @PersonImageType Varchar(255) As Begin Insert into Person (PersonEmail, PersonName, PersonSex, PersonDOB, PersonImage, PersonImageType) Values (@PersonEmail, @PersonName, @PersonSex, @PersonDOB, @PersonImage, @PersonImageType) End Go

下面就是完整的代碼,拷貝即可運行:

//---------------VB。NET-------------------<%@ Import Namespace="System.IO" %> <%@ Import Namespace="System.Data.SqlClient" %> <%@ Import Namespace="System.Data" %> <%@ Page Language="vb" %> <HTML> <HEAD> <title>向SQL Server插入圖片</title> <script runat="server"> Public Sub AddPerson(sender As Object, e As EventArgs) Dim intImageSize As Int64 Dim strImageType As String Dim ImageStream As Stream ' 獲得圖片的大小 intImageSize = PersonImage.PostedFile.ContentLength ' 獲得圖片類型 strImageType = PersonImage.PostedFile.ContentType '讀取圖片 ImageStream = PersonImage.PostedFile.InputStream Dim ImageContent(intImageSize) As Byte Dim intStatus As Integer intStatus = ImageStream.Read(ImageContent, 0, intImageSize) ' 創建Connection和Command對象 Dim strCnn As String = "Data Source=.;Initial Catalog=mxh;User Id=sa;Password=;" Dim myConnection As New SqlConnection(strCnn) Dim myCommand As New SqlCommand("sp_person_isp", myConnection) ' 使用存儲過程 myCommand.CommandType = CommandType.StoredProcedure ' 向存儲過程添加參數 Dim prmEmail As New SqlParameter("@PersonEmail", SqlDbType.VarChar, 255) prmEmail.Value = txtPersonEmail.Text myCommand.Parameters.Add(prmEmail) Dim prmName As New SqlParameter("@PersonName", SqlDbType.VarChar, 255) prmName.Value = txtPersonName.Text myCommand.Parameters.Add(prmName) Dim prmSex As New SqlParameter("@PersonSex", SqlDbType.Char, 1) If sexMale.Checked Then prmSex.Value = "M" Else prmSex.Value = "F" End If myCommand.Parameters.Add(prmSex) Dim prmPersonDOB As New SqlParameter("@PersonDOB", SqlDbType.DateTime) prmPersonDOB.Value = txtPersonDob.Text myCommand.Parameters.Add(prmPersonDOB) Dim prmPersonImage As New SqlParameter("@PersonImage", SqlDbType.Image) prmPersonImage.Value = ImageContent myCommand.Parameters.Add(prmPersonImage) Dim prmPersonImageType As New SqlParameter("@PersonImageType", SqlDbType.VarChar, 255) prmPersonImageType.Value = strImageType myCommand.Parameters.Add(prmPersonImageType) Try myConnection.Open() myCommand.ExecuteNonQuery() myConnection.Close() Response.Write("添加成功!") Catch SQLexc As SqlException Response.Write("添加失敗,原因:" & SQLexc.ToString()) End Try End Sub </script> </HEAD> <body style="FONT: 9pt 宋體"> <form enctype="multipart/form-data" runat="server" ID="Form1"> <asp:Table Runat="server" Width="50%" BorderWidth="1" BackColor="Beige" ID="Table1" Font-Name="宋體" Font-Size="9pt"> <asp:TableRow> <asp:TableCell ColumnSpan="2" BackColor="#ff0000"> <asp:Label ForeColor="#ffffff" font-bold="True" Runat="server" Text="添加新用戶" ID="Label1" /> </asp:TableCell> </asp:TableRow> <asp:TableRow> <asp:TableCell HorizontalAlign="Right"> <asp:Label Runat="server" Text="姓名" ID="Label2" /> </asp:TableCell> <asp:TableCell> <asp:TextBox id="txtPersonName" Runat="server" /> </asp:TableCell> </asp:TableRow> <asp:TableRow> <asp:TableCell HorizontalAlign="Right"> <asp:Label Runat="server" Text="電子郵件" ID="Label3" /> </asp:TableCell> <asp:TableCell> <asp:TextBox id="txtPersonEmail" Runat="server" /> </asp:TableCell> </asp:TableRow> <asp:TableRow> <asp:TableCell HorizontalAlign="Right"> <asp:Label Runat="server" Text="性別" ID="Label4"/> </asp:TableCell> <asp:TableCell> <asp:RadioButton GroupName="sex" Text="男" ID="sexMale" Runat="server" /> <asp:RadioButton GroupName="sex" Text="女" ID="sexFeMale" Runat="server" /> </asp:TableCell> </asp:TableRow> <asp:TableRow> <asp:TableCell HorizontalAlign="Right"> <asp:Label Runat="server" Text="出生日期" ID="Label5"/> </asp:TableCell> <asp:TableCell> <asp:TextBox id="txtPersonDOB" Runat="server" /> </asp:TableCell> </asp:TableRow> <asp:TableRow> <asp:TableCell HorizontalAlign="Right"> <asp:Label Runat="server" Text="照片" ID="Label6"/> </asp:TableCell> <asp:TableCell> <input type="file" id="PersonImage" runat="server" NAME="PersonImage" /></asp:TableCell> </asp:TableRow> <asp:TableRow> <asp:TableCell ColumnSpan="2" HorizontalAlign="Center"> <asp:Button Text=" 添 加 " OnClick="AddPerson" Runat="server" ID="Button1"/> </asp:TableCell> </asp:TableRow> </asp:Table> </form> </body> </HTML>

//------------------------------------------------------------------------------------------

C#版的(翻譯孟老師的^_^)
aspx:
<%@ Page language="c#" Codebehind="Register.aspx.cs" AutoEventWireup="false" Inherits="shop.Register" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>註冊</title>
</HEAD>
<body style="FONT-SIZE: 12px">
<form id="Form1" method="post" runat="server">
<FONT face="宋體">
<TABLE id="Table1" cellSpacing="0" cellPadding="0" width="50%" align="center" bgColor="beige"
border="0">
<TR>
<TD bgColor="#cccc66" colSpan="2" height="25" rowSpan="">添加新用戶</TD>
</TR>
<TR>
<TD>姓名</TD>
<TD>
<asp:TextBox id="txtPersonName" runat="server"></asp:TextBox></TD>
</TR>
<TR>
<TD>電子郵件</TD>
<TD>
<asp:TextBox id="txtPersonEmail" runat="server"></asp:TextBox></TD>
</TR>
<TR>
<TD>性別</TD>
<TD>
<asp:RadioButton GroupName="sex" Text="男" ID="sexMale" Runat="server" />
<asp:RadioButton GroupName="sex" Text="女" ID="sexFeMale" Runat="server" />
</TD>
</TR>
<TR>
<TD>出生日期</TD>
<TD>
<asp:TextBox id="txtPersonDOB" runat="server"></asp:TextBox></TD>
</TR>
<TR>
<TD>照片</TD>
<TD><INPUT type="file" id="personImage" name="PersonImage" runat="server"></TD>
</TR>
<TR>
<TD align="center" colSpan="2">
<asp:Button id="Button1" OnClick="AddPerson" runat="server" Text="添加"></asp:Button>
</TD>
</TR>
</TABLE>
</FONT>
</form>
</body>
</HTML>
aspx.cs:
using System;
using System.IO;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Configuration;
namespace shop
{
/// <summary>
/// Register 的摘要說明。
/// </summary>
public class Register : System.Web.UI.Page
{
protected System.Web.UI.WebControls.TextBox txtPersonName;
protected System.Web.UI.WebControls.TextBox txtPersonEmail;
protected System.Web.UI.WebControls.RadioButton sexMale;
protected System.Web.UI.WebControls.RadioButton sexFeMale;
protected System.Web.UI.WebControls.TextBox txtPersonDOB;
protected System.Web.UI.HtmlControls.HtmlInputFile personImage;
protected System.Web.UI.WebControls.Button Button1;

private void Page_Load(object sender, System.EventArgs e)
{
// 在此處放置用戶代碼以初始化頁面
}
public void AddPerson(object sender, System.EventArgs e)
{
int intImageSize;
string strImageType;
Stream ImageStream;
intImageSize = personImage.PostedFile.ContentLength; // 文件大小
strImageType = personImage.PostedFile.ContentType; // 文件類型
ImageStream = personImage.PostedFile.InputStream;
byte[] ImageContent = new byte[intImageSize];
int intStatus = ImageStream.Read(ImageContent, 0, intImageSize);

// 寫入數據庫
string strConn = ConfigurationSettings.AppSettings["ConnectionString"];
SqlConnection myConnection = new SqlConnection(strConn);
SqlCommand myCommand = new SqlCommand("sp_person_isp", myConnection);
myCommand.CommandType = CommandType.StoredProcedure;

myCommand.Parameters.Add("@PersonEmail", SqlDbType.VarChar, 255).Value = txtPersonEmail.Text;
myCommand.Parameters.Add("@PersonName", SqlDbType.VarChar, 255).Value = txtPersonName.Text;
myCommand.Parameters.Add("@PersonSex", SqlDbType.Char, 1);
if(sexMale.Checked)
myCommand.Parameters["@PersonSex"].Value = "M";
else
myCommand.Parameters["@PersonSex"].Value = "F";
myCommand.Parameters.Add("@PersonDOB", SqlDbType.DateTime).Value = txtPersonDOB.Text;
myCommand.Parameters.Add("@PersonImage", SqlDbType.Image).Value = ImageContent;
myCommand.Parameters.Add("@PersonImageType", SqlDbType.VarChar, 255).Value = strImageType;

try
{
myConnection.Open();
myCommand.ExecuteNonQuery();
myConnection.Close();
Response.Write("添加成功!");
}
catch(System.Exception SQLExe)
{
Response.Write("添加失敗!原因:"+SQLExe.ToString());
}
}

#region Web 窗體設計器生成的代碼
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: 該調用是 ASP.NET Web 窗體設計器所必需的。
//
InitializeComponent();
base.OnInit(e);
}

/// <summary>
/// 設計器支持所需的方法 - 不要使用代碼編輯器修改
/// 此方法的內容。
/// </summary>
private void InitializeComponent()
{    
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章