package com.example.demo.JDBC;

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/test";
            String dbUser = "JackyMa";
            String dbPass = "0.";
            conn = DriverManager.getConnection(dbUrl, dbUser, dbPass);//注意是三个参数
        }
        catch (SQLException e)
        {
            e.printStackTrace();
        }
        return conn;
    }

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

        Connection conn = getConn();//此处为通过自己写的方法getConn()获得连接
        PreparedStatement preparedStatement = null;
        String username = "";
        String password = "";
        try
        {
            preparedStatement = conn.prepareStatement(sql);
            preparedStatement.setString(1, loginname);
            ResultSet rs = preparedStatement.executeQuery();

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