Idea使用Maven连接MySQL数据库

连接MySQL数据库的步骤:
1.添加数据库
Idea使用Maven连接MySQL数据库
2.填写连接信息如图
Idea使用Maven连接MySQL数据库
3.填写连接信息完之后,需要记一下jar包的位置,用于添加jar包
Idea使用Maven连接MySQL数据库
4.显示jar包信息
Idea使用Maven连接MySQL数据库
5.添加文件夹命名java,并将其设为源文件夹
Idea使用Maven连接MySQL数据库
6.添加连接数据库的jar包
Idea使用Maven连接MySQL数据库
7.在java文件夹里右键添加java类文件
Idea使用Maven连接MySQL数据库
8.运行java的main,查询数据库成功
Idea使用Maven连接MySQL数据库

步骤7里的java类文件代码:
import java.sql.*;

public class ConnMysql {
public static void main(String[] args) {
String sql = “select * from t_black_list”;
Connection conn = null;
ResultSet rs = null;
PreparedStatement ps = null;
try {
//加载驱动
Class.forName(“com.mysql.jdbc.Driver”);
long start = System.currentTimeMillis();
//建立连接
conn = DriverManager.getConnection(url:“jdbc:mysql//localhost:3306/pay”,user:“root”,password:“123”);
long end = System.currentTimeMillis();
System.out.println(“建立连接耗时:”+(end-start)+“ms 毫秒”);
//创建PreparedStatement对象
ps = conn.prepareStatement(sql);
//执行SQL语句
rs = ps.executeQuery();
System.out.println(“id\tname\tidcard\t\tmobile”);
while(rs.next()){
System.out.println(rs.getInt(columnIndex:1)+"\t"+rs.getString(columnIndex:2)
+"\t\t"+rs.getString(columnIndex:3)+rs.getString(columnIndex:3));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}finally{
try {
if(rs!=null){
rs.close();
}
} catch (Exception e) {
}
try {
if(ps!=null){
ps.close();
}
} catch (Exception e) {
}
try {
if(conn!=null){
conn.close();
}
} catch (Exception e) {
}
}
}
}