driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/bjpowernode?useUnicode=true&characterEncoding=utf8&useSSL=false
user=root
password=root
ResourceBundle jdbc = ResourceBundle.getBundle("资源名");
注意,错误的写法:ResourceBundle.getBundle("资源名.properties")
举例:(刚才类路径下创建的JDBC.properties)
ResourceBundle jdbc = ResourceBundle.getBundle("JDBC");
String driver = jdbc.getString("driver");
String url = jdbc.getString("url");
String user = jdbc.getString("user");
String password = jdbc.getString("password");
package com.happy.lesson1;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ResourceBundle;
public class JDBCTest04 {
public static void main(String[] args) throws Exception {
ResourceBundle jdbc = ResourceBundle.getBundle("JDBC");
String driver = jdbc.getString("driver");
String url = jdbc.getString("url");
String user = jdbc.getString("user");
String password = jdbc.getString("password");
//1.注册驱动
Class.forName(driver);
//2.获取连接
Connection conn = DriverManager.getConnection(url, user, password);
//3.获取数据库操作对象
Statement stmt = conn.createStatement();
//4.执行sql
String sql = "update dept set dname = ‘销售部2‘,loc = ‘天津2‘ where deptno = 20";
int i = stmt.executeUpdate(sql);
//5.处理结果集
System.out.println((i==1)?"修改成功":"修改失败");
//6.关闭资源
stmt.close();
conn.close();
}
}
运行前:
运行后:
为什么需要把信息写到配置文件中呢?
因为数据库的账号和密码一般都在用户手上,由用户自己修改,没理由Java程序员问用户要账号和密码,万一这个程序员要到密码后删库跑路了呢?这就太不安全了,所以信息写到配置文件中,由用户填写就好。
原文:https://www.cnblogs.com/happy-lin/p/14981022.html