一、理论介绍
第一步:注册驱动

Class.forName("com.mysql.cj.jdbc.Driver");

第二步:建立连接

Connection con = DriverManager.getConnection(url,user,passwd);

url资源定位符

jdbc:mysql://localhost:port/databasename?useSSL=false&serverTimezone=UTC

user数据库用户名(root)
passwd数据库密码
第三步:获取数据库操作对象

PreparedStatement sta = con.preparestatement(sql);

sql代表的是sql语句的框架,例如:

String sql = “select * from massage where account = ? and pwd = ?”

?占位符(只能代表一个值,不能有‘’)

sta.setString(1,account);
sta.setString(2,pwd);

意为第一个定位符代表account,第二个代表pwd
第四步:执行功能(DQL,DML)
DQL

ResultSet res = sta.executeQuery();
sta.getString(columnindex:1);

第五步:关闭通道

res.close()
sta.close();
con.close();

二、实操
1 导入mysql-coonnector-java包
① 官网下载完包后,解压
图片说明
②在IDEA中导入jar包,先打开project structure
图片说明
随后点击➕,找到jar包,导入即可
图片说明
2 代码展示
此代码利用jdbc结合配置文件来控制对数据库的访问,不需要每次都修改代码,此jdbc程序可以多次复用。

public class StateCon {
    public static void main(String[] args) {
        Connection con = null;
        PreparedStatement sta = null;
        ResultSet res = null;
        String url = ResourceBundle.getBundle("Properties").getString("url");
        String user = ResourceBundle.getBundle("Properties").getString("user");
        String passwd = ResourceBundle.getBundle("Properties").getString("passwd");
        String sql = ResourceBundle.getBundle("Properties").getString("sql");
        String account = ResourceBundle.getBundle("Properties").getString("account");
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            con = DriverManager.getConnection(url,user,passwd);
            sta = con.prepareStatement(sql);
            sta.setString(1,account);
            res = sta.executeQuery();
            while(res.next()){
                System.out.println(res.getString(1));
                System.out.println(res.getString(2));
                System.out.println(res.getString(3));
                System.out.println(res.getString(4));
            }

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                res.close();
                sta.close();
                con.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }

        }
    }
}

配置文件properties.properties如下:

url=jdbc:mysql://localhost:3306/wxx?useSSL=false&serverTimezone=UTC
user=root
passwd=123456
sql=select * from wx where id=?
account=3;

附上配置文件和源文件的路径
图片说明