java之操作mysql常用方法

一般引用mysql-connector-java这个包。

package DBManager;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.Set;

import MyClient.ArrivalCities;
import MyClient.LineInfos;
import MyClient.TrainLineInfo;

public class DBHelper {

    private static final String DRIVER = "com.mysql.jdbc.Driver";
    private static final String URL = "jdbc:mysql://localhost:3306/traininfo";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "123abcd";
    Connection conn = null;
    ResultSet result = null;
    PreparedStatement statement = null;
    PreparedStatement stateInsert = null;
    PreparedStatement stateUnlock = null;

    public Connection getConnection() {
        try {
            Class.forName(DRIVER);
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return conn;
    }

    public ResultSet executeQuery(String sql) {
        conn = this.getConnection();
        try {
            statement = conn.prepareStatement(sql);
            result = statement.executeQuery();
            return result;
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println("query data failed");
        }
        return null;
    }

    public ResultSet findTrainLinesByDate(String start_city, String date) {
        String dateStr = dateToString(date);
        ResultSet result = this.executeQuery("select name,start_time from "
                + "line_" + dateStr + "_info " + "where start_city='"
                + start_city + "' and date='" + date + "'");
        return result;
    }

    public ResultSet findArrivalCities(String city, String line) {
        ResultSet result = this
                .executeQuery("select distinct arrival_city from " + city
                        + "_city_info where line_num='" + line + "'");
        return result;
    }

    public ArrivalCities getAllArrivalCities(String startCity, String date) {
        ArrivalCities cities = new ArrivalCities();
        Set<String> list = new HashSet<String>();
        ResultSet lines = this.findTrainLinesByDate(startCity, date);
        try {
            while (lines.next()) {
                ResultSet arrivals = this.findArrivalCities(startCity,
                        lines.getString("name"));
                while (arrivals.next()) {
                    list.add(arrivals.getString("arrival_city"));
                }
            }
            if (list.size() > 0) {
                cities.setCities(list);
                return cities;
            }
            return null;
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    public LineInfos getAllLineInfos(String startCity, String arrivalCity,
            String date) {
        LineInfos lineinfos = new LineInfos();
        ResultSet lines = this.findTrainLinesByDate(startCity, date);
        if (lines != null) {
            try {
                while (lines.next()) {
                    String name = lines.getString("name");
                    ResultSet result = this.executeQuery("select price from "
                            + startCity + "_city_info where arrival_city="
                            + '"' + arrivalCity + '"' + " and line_num=" + '"'
                            + name + '"');
                    if (result.next()) {
                        TrainLineInfo train = new TrainLineInfo(name,
                                result.getInt("price"),
                                lines.getLong("start_time"));
                        lineinfos.getList().add(train);
                    }
                }
                return lineinfos;
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return null;
    }

    public ResultSet findNumOfSellSeats(String date, String line) {
        String dateStr = dateToString(date);
        ResultSet result = this.executeQuery("SELECT count(id) as num from "
                + line + "_" + dateStr + "_info where is_out=1");
        return result;
    }

    public String dateToString(String date) {
        String[] result = date.split("-");
        StringBuilder sb = new StringBuilder();
        for (String ss : result) {
            sb.append(ss);
        }
        return sb.toString();
    }
    
    //购票,更新数据库信息
    public void getBuyTicket(String dep_city,String arr_city, String date, String line){
        String seat = getProperSeat(dep_city, line, date);
        String sql = "update ";
        
    }

    public boolean executeDelete(String sql) {
        conn = this.getConnection();
        try {
            statement = conn.prepareStatement(sql);
            if (statement.executeUpdate() > 0) {
                return true;
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            System.out.println("delete data failed");
            e.printStackTrace();
        }
        return false;
    }

    public boolean executeUpdate(String sql) {
        conn = this.getConnection();
        try {
            statement = conn.prepareStatement(sql);
            if (statement.executeUpdate() > 0) {
                return true;
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            System.out.println("update data failed");
            e.printStackTrace();
        }
        return false;
    }

    public boolean executeInsert(String sql, String date, String line) {
        conn = this.getConnection();
        String lockSql = "lock tables " + line + "_" + date + "_info write";
        String unlockSql = "unlock tables";
        try {
            stateInsert = conn.prepareStatement(lockSql);
            statement = conn.prepareStatement(sql);
            stateUnlock = conn.prepareStatement(unlockSql);
            stateInsert.executeQuery();
            if (statement.executeUpdate() > 0) {
                stateUnlock.executeQuery();
                return true;
            }
            stateUnlock.executeQuery();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            System.out.println("insert data failed");
            e.printStackTrace();
        }
        return false;
    }

}

 

posted @ 2013-12-06 16:52  楠楠IT  阅读(558)  评论(0编辑  收藏  举报