连接MySQL(maven)
1、在maven的pom.xml文件中添加依赖
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
2、新建properties文件保存连接信息
url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false
username=root
password=
3、utils包中创建工具类
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
public class MysqlUtil {
/**
* 创建数据库连接
* @return
* con 数据库连接
*/
public static Connection getConnection() {
Connection con=null;
try {
//加载属性文件,读取数据库连接配置信息
Properties pro = new Properties();
try {
InputStream in=MysqlUtil.class.getClassLoader().getResourceAsStream("mysql.properties");
pro.load(in);
} catch (IOException e) {
System.out.println("未找到配置文件!!!");
}
String url = pro.getProperty("url");
String username = pro.getProperty("username");
String password = pro.getProperty("password");
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(url, username, password);// 创建数据连接
} catch (SQLException e) {
e.printStackTrace();
System.out.println("数据库连接失败");
} catch (ClassNotFoundException e) {
throw new RuntimeException("驱动类找不到");
}
return con;
}
/**
* 关闭数据库
* @param con
* @param stm
* @param rs
*/
public static void close(Connection con, Statement stm, ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (stm != null) {
try {
stm.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (con != null) {
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
4、在数据库中创建测试库并编写测试程序
import java.sql.*;
public class test_sql {
public static void main(String[] args) {
Connection con = null;
Statement stm = null;
ResultSet rs = null;
try {
con = MysqlUtil.getConnection();
String sql = "SELECT * FROM test_user";
stm = con.createStatement();
rs = stm.executeQuery(sql);
System.out.println("查询结果:");
while (rs.next()) {
String name = rs.getString("name");
System.out.println(name);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
MysqlUtil.close(con, stm, rs);
}
}
}
5、运行结果

6、总结
数据库配置文件中很多变量是经常改变的,使用properties文件这样做也是为了方便用户,让用户能够脱离程序本身去修改相关的变量设置。同时把数据库连接做成工具类,方便后面引用,简化代码。
转载自:https://juejin.cn/post/6844904131040133133