Java-web的JDBC的实现

//jar包的导入,jsp-api.jar,mysql-connector-java-5.0.8-bin.jar,记得Build Path,servlet-api.jar,
JAVA-- class的编写

package com.jdbcdemo.servlet;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class ProductDao {
public void add() {}
public void update() {}
public void delete() {}
public void queryById(String id) {}
public static List queryAll() {
List allproduct=new ArrayList();
String driver=“com.mysql.jdbc.Driver”;
//String url=“jdbc:mysql://localhost:3306/itcaststore”;
String url=“jdbc:mysql://localhost:3306/itcaststore?useUnicode=true&characterEncoding=utf8”;
String user=“root”;
String password=“root”;
//1.加载并注册数据库驱动
//声明连接对象
Connection connection=null;
PreparedStatement statement=null;//执行SQL语句对象
try {
//访问数据库的步骤
//1.加载驱动
Class.forName(driver);
//2.通过DriverManager获取连接对象connection
connection=DriverManager.getConnection(url, user, password);
//3.通过连接对象获取命令对象PreparedStatement执行SQL语句
statement=connection.prepareStatement(“SELECT * FROM products”);
//执行过后返回一个结果集
ResultSet resultSet= statement.executeQuery();
while (resultSet.next()) {
Product product=new Product();
System.out.println(resultSet.getString(“id”));
System.out.println(resultSet.getString(“name”));
System.out.println(resultSet.getDouble(“price”));
allproduct.add(product);
}
connection.close();
}catch (SQLException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return allproduct;
}
public static void main(String[] args) {
queryAll();

}

}
//
<%@ page language=“java” contentType=“text/html; charset=UTF-8”
pageEncoding=“UTF-8”%>
<%@page import=“java.util.*” %>
<%@page import=“com.jdbcdemo.servlet.ProductDao” %>//放入项目的包名称
<%@page import=“com.jdbcdemo.servlet.Product” %>//放入项目的包名称

首页

全部商品信息

<% List allproducts=ProductDao.queryAll(); for(Product pp :allproducts){ %>

<%=pp.getName() %> <%=pp.getPrice() %>

 <%} %>

你可能感兴趣的:(Java-Web)