这篇博客主要讲解如何IntelliJIdea2019.3开发工具编写Java代码链接数据库
第一步:编写Java代码
package com.mysql;
import java.sql.*;
public class test {
public static void main(String[] args) {
//加载驱动器类
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
//驱动器路径
String url="jdbc:mysql://localhost:3306/lianxi";
//查询语句
String sql="select * from student";
//加载链接
try {
Connection con = DriverManager.getConnection(url, "root", "123456");
//创建statement对象
Statement sta = con.createStatement();
//执行查询语句
ResultSet res = sta.executeQuery(sql);
//处理结果
while(res.next()){
System.out.println(
"姓名:"+ res.getString(1)+ "年龄"+res.getInt(2)
);
}
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
第二步:加载Jar包依赖:点击File---》点击Project Structure---》点击Module---》点击+号---》JAR or directories
第三步:运行主方法:最后运行成功