日期:2014-05-16  浏览次数:20390 次

JSP实现MYSQL5.1存入图片
connection.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@ page import="java.sql.*" errorPage="" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>

<p>
<table border="1">
  <tr>
    <td>图片Num</td>
    <td>图片</td>
  </tr>
  <%
    Connection conn = null;
 Statement  stmt = null;
    ResultSet   rs  = null;
 request.setCharacterEncoding("utf-8");
 String  uri = "jdbc:mysql://localhost:3306/test";//使用的是test数据库
 String  sql = "select picNum from pic "; //我建图片表 pic
 try{
  Class.forName("com.mysql.jdbc.Driver");
  }catch(Exception e){
     out.print(e);
     }

 try{
  conn = DriverManager.getConnection(uri,"root","root");//我的用户名是 root ,密码 是 soft 根据你的需要 更改
  stmt = conn.createStatement();
    rs = stmt.executeQuery(sql);
    while(rs.next()){
%>
  <tr>
    <td><%=rs.getString("picNum")%></td>
    <td><img src="tupian/<%=rs.getString("picNum")%>"></td>
  </tr>
  <%
      }
 }catch(Exception e){
   out.print(e);
 }
%>
</table>


</body>
</html>


数据库的设计:
附录:sql脚本
use test;
create table pic(
   id int primary key auto_increment,
   picNum varchar(10) unique
);




然后插入数据:
insert into pic(picNum) values('1.jpg');
insert into pic(picNum) values('2.jpg');
insert into pic(picNum) values('3.jpg');
insert into pic(picNum) values('4.jpg');
insert into pic(picNum) values('5.jpg');
insert into pic(picNum) values('6.jpg');
insert into pic(picNum) values('7.jpg'); 


结果图: