ASP.NET从SQL Server数据库提取图片并显示在DataGrid
使用Gridview绑定数据库中的图片(转载)
注:此系列记录在我实际开发中遇到的问题和收藏一些技巧文章。
我们都知道,在Gridview中不能直接去绑定数据库中的图片,我们可以利用HttpHandler很容易的完成这个任务,在这里我记录一下这个过程。
1.上传图片存储到数据库中
在数据库中创建一个表,添加一下3个字段:
步骤一:在Web页面中拖一个FileUpload 控件,一个文本框用于输入名称和提交上传按钮
<asp:FileUpload ID="fuImage" runat="server" /><br />
<asp:TextBox ID="txtImageName" runat="server"/><br />
<asp:Button ID="btnUpload" runat="server" onClick="btnUpload_Click" Text="Upload" />
步骤二:在Web.Config文件内配置连接字符串。
<add name="ConnectionString" connectionString="Data Source=.\SQLEXPRESS;
AttachDbFilename=|DataDirectory|\Image.mdf;Integrated Security=True;
User Instance=True" providerName="System.Data.SqlClient"/>
步骤三:把下面的代码复制到上传按钮事件中。
protected void btnUpload_Click(object sender, EventArgs e)
{
Stream imgStream = fuImage.PostedFile.InputStream;
int imgLen = fuImage.PostedFile.ContentLength;
string imgName = txtImageName.Text;
byte[] imgBinaryData = new byte[imgLen];
int n = imgStream.Read(imgBinaryData,0,imgLen);
//use the web.config to store the connection string
SqlConnection connection = new SqlConnection(ConfigurationManager.
ConnectionStrings["connectionString"].ConnectionString);
SqlCommand command = new SqlCommand("INSERT INTO Image (imagename,image)
VALUES ( @img_name, @img_data)", connection);
SqlParameter param0 = new SqlParameter("@img_name", SqlDbType.VarChar, 50);
param0.Value = imgName;
command.Parameters.Add(param0);
SqlParameter param1 = new SqlParameter("@img_data", SqlDbType.Image);
param1.Value = imgBinaryData;
command.Parameters.Add(param1);
connection.Open();
int numRowsAffected = command.ExecuteNonQuery();
connection.Close();
}
2.利用HttpHandler从数据库中读取图片
创建
相关文档:
首页:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head ......
//private string datapatch = ConfigurationSettings.AppSettings["acessconn"];//数据库地址
private string datapatch = "db/global.asa";//数据库地址
///
/// 取得dataset
//
/// 查询语句
///
public DataSet GetDataSet(string Commandtext)
{&nbs ......
http://www.umgr.com/blog/PostView.aspx?bpId=36294
1. 执行sql语句
int sqlite3_exec(sqlite3*, const char *sql, sqlite3_callbacksql 语法
, void *, char **errmsg );
这就是执行一条 sql 语句的函数。
第1个参数不再说了,是前面open函数得到的指针。说了是关键数据结构。
第2个参数const char ......
<%
SQL1 = "update table1 set a=b where id=1"
Conn.ExeCute SQL1
SQL2 = "update table2 set a=b where id=2"
Conn.ExeCute SQL2
SQL3 = "update table3 set a=b where id=3"
Conn.ExeCute SQL3
%>
&nb ......