maven项目连接MySQL方式(使用原生的jdbc)
更新时间:2026年03月12日 10:40:37 作者:小石潭记丶
文章介绍了如何在项目中添加依赖、组织目录结构、配置数据库连接属性以及编写工具类,并分享了个人经验,鼓励读者参考和支持脚本之家
1.引入依赖
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.45</version> </dependency>
2.项目目录结构

jdbc.properties内容
driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/shiro?useUnicode=true&characterEncoding=utf-8&useSSL=false username=root password=123456
util类
package com.cxb.shiro;
import java.io.IOException;
import java.util.Properties;
/**
* 获取资源文件的util
* @author 81046
*
*/
public class PropertiesUtil {
static Properties properties = new Properties();
public PropertiesUtil() {
}
public static boolean loadFile(String fileName){
try {
properties.load(PropertiesUtil.class.getClassLoader().getResourceAsStream(fileName));
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
public static String getPropertyValue(String key){
return properties.getProperty(key);
}
}
package com.cxb.shiro;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class JdbcUtils {
//通过上面的工具就可以获取到properties文件中的键值从而可以加载驱动 获取链接 从而 可以增删改查
private static Connection conn = null;
public static Connection getConn(){
PropertiesUtil.loadFile("jdbc.properties");
String driver = PropertiesUtil.getPropertyValue("driver");
String url = PropertiesUtil.getPropertyValue("url");
String username = PropertiesUtil.getPropertyValue("username");
String password = PropertiesUtil.getPropertyValue("password");
try {
Class.forName(driver);
conn = DriverManager.getConnection(url,username,password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
close();
}
return conn;
}
public static void close(){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* 通过用户名到数据库中获取凭证密码
* @param userName
* @return
*/
private static String getPasswordByUserName(String userName) {
//SQL语句
String sql = "select password from users where username = " +"'" + userName+"'";
Connection conn = JdbcUtils.getConn();
Statement stmt=null;
ResultSet ret = null;
String password=null;
try {
stmt = conn.createStatement();
//执行语句,得到结果集
ret = stmt.executeQuery(sql);
while (ret.next()) {
//这里只查询的密码
password = ret.getString(1);
}
ret.close();
conn.close();//关闭连接
} catch (SQLException e1) {
e1.printStackTrace();
}
return password;
}总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
JavaEE SpringMyBatis是什么? 它和Hibernate的区别及如何配置MyBatis
这篇文章主要介绍了JavaEE Spring MyBatis是什么? 它和Hibernate的区别有哪些?如何配置MyBatis?本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下2020-08-08
Java Mybatis框架增删查改与核心配置详解流程与用法
MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO为数据库中的记录2021-10-10


最新评论