package com.example.demo.JDBC;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

import java.sql.*;


/**
 *      佛曰:
 *              写字楼里写字间，写字间里程序员；
 *              程序人员写程序，又拿程序换酒钱。
 *              酒醒只在网上坐，酒醉还来网下眠；
 *              酒醉酒醒日复日，网上网下年复年。
 *              但愿老死电脑间，不愿鞠躬老板前；
 *              奔驰宝马贵者趣，公交自行程序员。
 *              别人笑我忒疯癫，我笑自己命太贱；
 *              不见满街漂亮妹，哪个归得程序员？
 */

public class ConnectDB {
    public Connection getConn()
    {
        Connection conn=null;
        try
        {
            String dbDriver = "com.mysql.cj.jdbc.Driver";
            Class.forName(dbDriver);
        }
        catch (ClassNotFoundException e)
        {
            e.printStackTrace();
        }
        try
        {
            //根据实际情况变化
            String dbUrl = "jdbc:mysql://localhost:3306/iams?serverTimezone=GMT";
            String dbUser = "root";
            String dbPass = "root";
            conn = DriverManager.getConnection(dbUrl, dbUser, dbPass);//注意是三个参数
        }
        catch (SQLException e)
        {
            e.printStackTrace();
        }
        return conn;
    }
    Connection conn = getConn();//此处为通过自己写的方法getConn()获得连接
    PreparedStatement preparedStatement = null;

    public String loginSystem(String loginname)
    {
        String sql = "select * from iams.user where username = ?";

        String username = "";
        String password = "";

        try
        {
            preparedStatement = conn.prepareStatement(sql);
            preparedStatement.setString(1, loginname);
            ResultSet rs = preparedStatement.executeQuery();

            if(rs.next())
            {
                username = rs.getString(1);//或者为rs.getString(1)，根据数据库中列的值类型确定，参数为第一列
                System.out.println(username);
                password = rs.getString(2);
                System.out.println(password);
            }
            //可以将查找到的值写入类，然后返回相应的对象
        }
        catch (SQLException e)
        {
            e.printStackTrace();
        }
        return (password);
    }

    public JsonArray initCombatants() throws SQLException {
        String sql = "select * from aircraft.combatants";
        preparedStatement = conn.prepareStatement(sql);
        ResultSet rs = preparedStatement.executeQuery();
        JsonArray Departments = new JsonArray();
        while(rs.next()){
            JsonObject Department = new JsonObject();
            Department.addProperty("name",rs.getString(2));
            Department.addProperty("establish",rs.getString(3));
            Department.addProperty("head", rs.getString(4));
            Department.addProperty("chief", rs.getString(5));
            Department.addProperty("incumbent", rs.getString(6));
            Department.addProperty("departure", rs.getString(7));
            Department.addProperty("state", rs.getString(8));
            Departments.add(Department);
        }
        return Departments;
    }
}
