1. 程式人生 > 其它 >java連線mysql8.0.28資料庫例項

java連線mysql8.0.28資料庫例項

首先說明,由於是8版本的資料庫,所以配置類的寫法上與5版本的有所區別,需要注意,同時用idea或eclipse時需要匯入jar包,jar包的下載連結:

https://dev.mysql.com/get/archives/mysql-connector-java-8.0/mysql-connector-java-8.0.28.zip

如果想要下載8版本不同的jar包只需要修改8.0.28為指定版本即可。

idea匯入jar包的方法如下:

 

 

 

 

 

 

 

 

 

 然後是程式碼部分,首先先建表:

CREATE TABLE `train_message` (
                                 `id` 
int NOT NULL AUTO_INCREMENT COMMENT '主鍵id', `train_name` varchar(20) NOT NULL COMMENT '列車名', `origin` varchar(30) NOT NULL COMMENT '始發地', `terminal` varchar(30) NOT NULL COMMENT '終到地', `departure_time`
timestamp NOT NULL COMMENT '出站時間', `state` varchar(10) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '正常' COMMENT '列車狀態', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8mb3

然後建立連線的配置類DbConfig.java,localhost是本機的ip地址,如果有伺服器就填伺服器的ip地址,message是資料庫的名字,這裡一張圖說下有很多新手誤解的名字

 

 

 

 

 

 

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 *  資料庫配置類
 *  @author 景苒
 */
public class DbConfig {
    public Connection dbConfig() throws SQLException {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        }catch (Exception e) {
            System.out.print("載入驅動失敗!");
            e.printStackTrace();
        }
        String url = "jdbc:mysql://localhost:3306/message?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true";
        String user = "root";
        String password = "123456";
        return DriverManager.getConnection(url, user, password);
    }
}

然後寫下主函式Main.java,這裡主函式的函式體可以在最後再寫,需要什麼功能就把註釋開啟就好,快捷註釋的方法,選中這句話,按ctrl加/,就能全註釋了。

import java.sql.SQLException;

/**
 * 主函式,呼叫功能
 * @author 景苒
 */
public class Main {
    public static void main(String[] args) throws SQLException {
//        new GetMessage().getMessage();
//        new UpdateTrainState().updateTrainState();
//        new InsertTrain().insertTrain();
//        new GetNumber().getNumber();
    }
}

然後是每個的功能:

1.查詢瀋陽到武漢的所有列車資訊,按出發時間先後排序

建GetMessage.java類

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 查詢瀋陽到武漢的所有列車資訊,按出發時間先後排序
 * @author 景苒
 */
public class GetMessage {
    public void getMessage() throws SQLException {
        Connection con = new DbConfig().dbConfig();
        String sql = "select * from `train_message` where origin = ? and terminal = ? ORDER BY departure_time ASC";
        String origin = "瀋陽";
        String terminal = "武漢";
        PreparedStatement ps = con.prepareStatement(sql);
        ps.setString(1, origin);
        ps.setString(2, terminal);
        ResultSet rs = ps.executeQuery();
        try {
            while (rs.next()) {
                System.out.println("列車名:" + rs.getString("train_name")
                        + " 始發站:" + rs.getString("origin")
                        + " 終到站:" + rs.getString("terminal")
                        + " 出發時間:" + rs.getString("departure_time")
                        + " 列車狀態:" + rs.getString("state"));
            }
        }catch (SQLException e) {
            e.printStackTrace();
        }finally {
            ps.close();
            con.close();
        }
    }
}

2.修改T2255列車的狀態為停運

建UpdateTrainState.java類

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * 修改T2255列車的狀態為停運
 * @author 景苒
 */
public class UpdateTrainState {
    public void updateTrainState() throws SQLException {
        Connection con = new DbConfig().dbConfig();
        String sql = "UPDATE `train_message` SET state = '停運' WHERE train_name = 'T2255'";
        Statement statement = con.createStatement();
        try {
            int i = statement.executeUpdate(sql);
            if (i > 0) {
                System.out.println("更新成功");
            }else {
                System.out.println("更新失敗");
            }
        }catch (SQLException e) {
            e.printStackTrace();
        }finally {
            statement.close();
            con.close();
        }
    }
}

3.新增一輛列車資訊(自己輸入)

 建InsertTrain.java類

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

/**
 * 新增一輛列車資訊(自己輸入)
 * 始發時間為timestamp型別,輸入時需要確保格式正確,如:2019-01-01 00:00:00
 * @author 景苒
 */
public class InsertTrain {
    public void insertTrain() throws SQLException {
        Connection con = new DbConfig().dbConfig();
        Scanner scanner = new Scanner(System.in);
        String sql = "insert into `train_message` values(null, ?, ?, ?, ?, default)";
        System.out.print("請輸入列車名:");
        String trainName = scanner.nextLine();
        System.out.print("請輸入始發站:");
        String origin = scanner.nextLine();
        System.out.print("請輸入終到站:");
        String terminal = scanner.nextLine();
        System.out.print("請輸入始發時間:");
        String departureTime = scanner.nextLine();
        PreparedStatement ps = con.prepareStatement(sql);
        ps.setString(1, trainName);
        ps.setString(2, origin);
        ps.setString(3, terminal);
        ps.setString(4, departureTime);
        try {
            int i = ps.executeUpdate();
            if (i > 0) {
                System.out.println("新增成功");
            }else {
                System.out.println("新增失敗");
            }
        }catch (SQLException e) {
            e.printStackTrace();
        }finally {
            ps.close();
            con.close();
        }
    }
}

4.查詢狀態為正常的列車數量

 建GetNumber.java類

import java.sql.Statement;

/**
 * 查詢狀態為正常的列車數量
 * @author 景苒
 */
public class GetNumber {
    public void getNumber() throws SQLException {
        Connection con = new DbConfig().dbConfig();
        String sql = "select count(state) from `train_message` where state = '正常'";
        Statement statement = con.createStatement();
        try {
            ResultSet resultSet = statement.executeQuery(sql);
            while (resultSet.next()) {
                System.out.println("狀態為正常的列車數量為:" + resultSet.getInt(1));
            }
        }catch (SQLException e){
            e.printStackTrace();
        }finally {
            statement.close();
            con.close();
        }
    }
}

最後附上navicat的屬性結構圖和樣例插入的語句

 

 

 資料根據自己需求自行寫入幾個就行,以上就是java連線mysql資料庫的例項程式碼,eclipse也大同小異,就匯入jar包的方式不同。