myeclipse 中java連線mysql、查詢測試

weixin_34320159發表於2018-02-28

前言

為了方便引入mysql的jar支援包,在此我選擇工程支援maven

環境準備

  • JDK
  • mysql伺服器(我採用xampp整合工具中的mysql)
  • myeclipse

順便推薦一篇文章:MySQL 5.7 版本的安裝及簡單使用(圖文教程)

先上工程結構圖

5438896-4d987511b00c3ed5.png
專案工程結構

建立新web project專案CzgWeb

為了方便引入mysql的jar支援包,在此我選擇工程支援maven。

5438896-6d3010b575d041b2.png
建立工程

在工程的pom.xml配置檔案中新增mysql依賴

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.32</version>
        <scope>provided</scope>
    </dependency>
5438896-6cdb3fe6b7ba77f7.png
pom.xml中配置

儲存後,在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)

5438896-7acef3be6061040b.png
執行DBHelper.java

連線測試結果

5438896-cdee03e1155bf6f7.png
測試結果

在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("沒有找到商品");
        }

}

5438896-172ac4ea2bebcc1c.png
查詢測試結果

相關文章