初用IDEA的spingboot第三步
建立数据库连接
1.准备数据库
新建数据库:打开navicat,连接mysql(也可以连接别的,一般用mysql),新建表。
2.配置文件
在idea中找到main/resources,新建file文件命名为db.properties(可起其他名称)
将一下内容粘贴在新建的db.properties中
#连接MYSQL数据库的配置文件 注:等号前后不要写空格
#驱动名
jdbcName=com.mysql.cj.jdbc.Driver
#数据库连接 (zyx是数据库名称,需要改成自己的数据库名称)
dbUrl=jdbc:mysql://localhost:3306/zyx?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false
#数据库的连接账号
dbName=root
#数据库的密码
dbPwd=123456
3.准备工具类
在idea中找到main/java/com.lezijie.note/util,在其中新建工具类DBUtil
//得到配置对象
private static Properties properties = new Properties();//接收配置文件中的键值对
static {
try {
//加载配置文件(输入流) 类加载器 获取资源 资源名
InputStream in=DBUtil.class.getClassLoader().getResourceAsStream("db.properties");
//通过load()方法将输入流的内容加载到配置文件对象中
properties.load(in);
//通过配置文件对象的个体property()方法获取驱动名,并加载驱动
Class.forName(properties.getProperty("jdbcName"));
} catch (Exception e) {
e.printStackTrace();
}
}
//获取数据库连接
public static Connection getConnection(){
Connection connection=null;
try {
//得到数据库连接的相关信息 数据库地址 数据库登录名 数据库密码
//定义字符串 将获取信息放入字符串中
String dbUrl=properties.getProperty("dbUrl");
String dbName=properties.getProperty("dbName");
String dbPwd=properties.getProperty("dbPwd");
//得到数据库连接
connection = DriverManager.getConnection(dbUrl,dbName,dbPwd);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return connection;
}
public static void close(ResultSet resultSet,
PreparedStatement preparedStatement,
Connection connection){
//判断资源对象如果不为空,则关闭
try {
if (resultSet != null){
resultSet.close();
}
if (preparedStatement != null){
preparedStatement.close();
}
if (connection != null){
connection.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通