javabean内容
package com.wmm.dbutil;
import java.sql.*;
public class Db {
private String driver;
private String url;
private String user;
private String pwd;
private Connection conn;
//默认连接参数设置
public Db(){
driver="com.microsoft.sqlserver.jdbc.SQLServerDriver";
url="jdbc:sqlserver://localhost;DatabaseName=jsp";
user="sai";
pwd="123";
}
//定制连接参数
public Db(String driver,String url,String user,String pwd){
this.driver=driver;
this.url=url;
this.user=user;
this.pwd=pwd;
}
//实现连接的方法
private void connect()throws Exception{
if(conn==null||conn.isClosed()){
Class.forName(driver);
conn=DriverManager.getConnection(url,user,pwd);
}
}
//封装关闭连接操作
public void closeConn()throws Exception{
if(conn==null&&!conn.isClosed()){
conn.close();
}
}
//封装简单查询与更新操作
public ResultSet query(String sql)throws Exception{
ResultSet rs=null;
this.connect();
Statement stat=conn.createStatement();
rs=stat.executeQuery(sql);
return rs;
}
public int update(String sql)throws Exception{
int flag=0;
this.connect();
Statement stat=conn.createStatement();
flag=stat.executeUpdate(sql);
return flag;
}
//封装预定义查询与更新操作
public PreparedStatement prepareStatement(String sql)throws Exception{
this.connect();
PreparedStatement pstat=null;
pstat=conn.prepareStatement(sql);
return pstat;
}
public ResultSet preparedQuery(PreparedStatement pstat)throws Exception{
ResultSet rs=null;
rs=pstat.executeQuery();
return rs;
}
public int preparedUpdate(PreparedStatement pstat)throws Exception{
int flag=0;
flag=pstat.executeUpdate();
return flag;
}
}
jsp内容
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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>网站首页</title>
</head>
<body>
<jsp:useBean id="db" class="com.wmm.dbutil.Db" scope="page"/>
<%@ page import="java.util.ArrayList"%>
<%@ page import="java.sql.*"%>
<%@ page import="com.wmm.dbutil.Db"%>
<%@ page import="com.wmm.valuebean.GoodsSingle"%>
<%! static ArrayList<GoodsSingle> goodslist=new ArrayList<GoodsSingle>();
static GoodsSingle single=new GoodsSingle();%>
<%
try{
ResultSet rs=db.query("select * from shopcar");
int index=0;
while(rs.next()){
%>
11111
<%
single.setName(rs.getString(1));
single.setPrice(rs.getFloat(2));
single.setNum(rs.getInt(3));
goodslist.add(index,single);
index++;
}
}catch(Exception e){
e.getStackTrace();
} %>
<%
session.setAttribute("goodslist",goodslist);
// response.sendRedirect("show.jsp"); //跳转到show.jsp页面显示商品
%>
</body>
</html>
Caption_1210
相关分类