前言
为了方便引入mysql的jar支持包,在此我选择工程支持maven
环境准备
- JDK
- mysql服务器(我采用xampp集成工具中的mysql)
- myeclipse
顺便推荐一篇文章:MySQL 5.7 版本的安装及简单使用(图文教程)
先上工程结构图
创建新web project项目CzgWeb
为了方便引入mysql的jar支持包,在此我选择工程支持maven。
在工程的pom.xml配置文件中添加mysql依赖
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.32</version>
<scope>provided</scope>
</dependency>
保存后,在Maven Dependencies中会有mysql对应的依赖包(不像android stuido中还得点击同步)
在src目录创建mysql连接帮助类DBHelper.java
为了方便java文件测试(不通过项目测试),我们直接在本DBHelper添加main方法,直接运行
package util;
import java.sql.Connection;
import java.sql.DriverManager;
public class DBHelper {
private static final String driver = "com.mysql.jdbc.Driver"; //数据库驱动
//连接数据库的URL地址
private static final String url="jdbc:mysql://localhost:3306/phpmyadmin?useUnicode=true&characterEncoding=UTF-8";
private static final String username="root";//数据库的用户名
private static final String password="";//数据库的密码
private static Connection conn=null;
//静态代码块负责加载驱动
static
{
try
{
Class.forName(driver);
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
//单例模式返回数据库连接对象
public static Connection getConnection() throws Exception
{
if(conn==null)
{
conn = DriverManager.getConnection(url, username, password);
return conn;
}
return conn;
}
public static void main(String[] args) {
try
{
Connection conn = DBHelper.getConnection();
if(conn!=null)
{
System.out.println("数据库连接正常!");
}
else
{
System.out.println("数据库连接异常!");
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}
运行测试(选择Java Application)
连接测试结果
在mysql的phpmyadmin数据库添加表items,并初始化数据
工具有http://localhost/phpmyadmin/ 管理
或 SQLyog
或Navicat
付sql语句
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for items
-- ----------------------------
DROP TABLE IF EXISTS `items`;
CREATE TABLE `items` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(50) DEFAULT NULL,
`city` VARCHAR(50) DEFAULT NULL,
`price` INT(11) DEFAULT NULL,
`number` INT(11) DEFAULT NULL,
`picture` VARCHAR(500) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=INNODB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of items
-- ----------------------------
INSERT INTO `items` VALUES ('1', '沃特篮球鞋', '佛山', '180', '500', '001.jpg');
INSERT INTO `items` VALUES ('2', '安踏运动鞋', '福州', '120', '800', '002.jpg');
INSERT INTO `items` VALUES ('3', '耐克运动鞋', '广州', '500', '1000', '003.jpg');
INSERT INTO `items` VALUES ('4', '阿迪达斯T血衫', '上海', '388', '600', '004.jpg');
INSERT INTO `items` VALUES ('5', '李宁文化衫', '广州', '180', '900', '005.jpg');
INSERT INTO `items` VALUES ('6', '小米3', '北京', '1999', '3000', '006.jpg');
INSERT INTO `items` VALUES ('7', '小米2S', '北京', '1299', '1000', '007.jpg');
INSERT INTO `items` VALUES ('8', 'thinkpad笔记本', '北京', '6999', '500', '008.jpg');
INSERT INTO `items` VALUES ('9', 'dell笔记本', '北京', '3999', '500', '009.jpg');
INSERT INTO `items` VALUES ('10', 'ipad5', '北京', '5999', '500', '010.jpg');
商品项目Items类
主要用于描述商品
package entity;
//商品类
public class Items {
private int id; // 商品编号
private String name; // 商品名称
private String city; // 产地
private int price; // 价格
private int number; // 库存
private String picture; // 商品图片
//保留此不带参数的构造方法
public Items()
{
}
public Items(int id,String name,String city,int price,int number,String picture)
{
this.id = id;
this.name = name;
this.city = city;
this.picture = picture;
this.price = price;
this.number = number;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public String getPicture() {
return picture;
}
public void setPicture(String picture) {
this.picture = picture;
}
@Override
public int hashCode() {
// TODO Auto-generated method stub
return this.getId()+this.getName().hashCode();
}
@Override
public boolean equals(Object obj) {
// TODO Auto-generated method stub
if(this==obj)
{
return true;
}
if(obj instanceof Items)
{
Items i = (Items)obj;
if(this.getId()==i.getId()&&this.getName().equals(i.getName()))
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
public String toString()
{
return "商品编号:"+this.getId()+",商品名称:"+this.getName();
}
}
创建业务逻辑类ItemsDAO,并运行ItemsDAO.java
同样也添加上了main的方法方便测试
package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import util.DBHelper;
import entity.Items;
//商品的业务逻辑类
public class ItemsDAO {
// 获得所有的商品信息
public ArrayList<Items> getAllItems() {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
ArrayList<Items> list = new ArrayList<Items>(); // 商品集合
try {
conn = DBHelper.getConnection();
String sql = "select * from items;"; // SQL语句
stmt = conn.prepareStatement(sql);
rs = stmt.executeQuery();
while (rs.next()) {
Items item = new Items();
item.setId(rs.getInt("id"));
item.setName(rs.getString("name"));
item.setCity(rs.getString("city"));
item.setNumber(rs.getInt("number"));
item.setPrice(rs.getInt("price"));
item.setPicture(rs.getString("picture"));
list.add(item);// 把一个商品加入集合
}
return list; // 返回集合。
} catch (Exception ex) {
ex.printStackTrace();
return null;
} finally {
// 释放数据集对象
if (rs != null) {
try {
rs.close();
rs = null;
} catch (Exception ex) {
ex.printStackTrace();
}
}
// 释放语句对象
if (stmt != null) {
try {
stmt.close();
stmt = null;
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
// 根据商品编号获得商品资料
public Items getItemsById(int id) {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
conn = DBHelper.getConnection();
String sql = "select * from items where id=?;"; // SQL语句
stmt = conn.prepareStatement(sql);
stmt.setInt(1, id);
rs = stmt.executeQuery();
if (rs.next()) {
Items item = new Items();
item.setId(rs.getInt("id"));
item.setName(rs.getString("name"));
item.setCity(rs.getString("city"));
item.setNumber(rs.getInt("number"));
item.setPrice(rs.getInt("price"));
item.setPicture(rs.getString("picture"));
return item;
} else {
return null;
}
} catch (Exception ex) {
ex.printStackTrace();
return null;
} finally {
// 释放数据集对象
if (rs != null) {
try {
rs.close();
rs = null;
} catch (Exception ex) {
ex.printStackTrace();
}
}
// 释放语句对象
if (stmt != null) {
try {
stmt.close();
stmt = null;
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
//获取最近浏览的前五条商品信息
public ArrayList<Items> getViewList(String list)
{
System.out.println("list:"+list);
ArrayList<Items> itemlist = new ArrayList<Items>();
int iCount=5; //每次返回前五条记录
if(list!=null&&list.length()>0)
{
String[] arr = list.split(",");
System.out.println("arr.length="+arr.length);
//如果商品记录大于等于5条
if(arr.length>=5)
{
for(int i=arr.length-1;i>=arr.length-iCount;i--)
{
itemlist.add(getItemsById(Integer.parseInt(arr[i])));
}
}
else
{
for(int i=arr.length-1;i>=0;i--)
{
itemlist.add(getItemsById(Integer.parseInt(arr[i])));
}
}
return itemlist;
}
else
{
return null;
}
}
//为了方便独立测试添加main方法
public static void main(String[] args) {
ItemsDAO idao = new ItemsDAO();
Items item = idao.getItemsById(Integer.parseInt("2"));
if (item !=null){
System.out.println(item.getCity());
System.out.println(item);
}else{
System.out.println("没有找到商品");
}
}