栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 前沿技术 > 大数据 > 大数据系统

JDBC学习(二) ---------通过配置文件和Java资源绑定器链接数据库

JDBC学习(二) ---------通过配置文件和Java资源绑定器链接数据库

目录
  • 一、创建数据库的配置文件
  • 二、在主程序中用资源绑定器的形式来获取各项数据


一、创建数据库的配置文件
在主程序的同一个包下新建一个文本文件
写入
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/MyDatabase?serverTimezone=GMT
user=root
password=.....
然后保存文件为db.properties

如图


二、在主程序中用资源绑定器的形式来获取各项数据
1. 获取配置文件对象
   ResouceBundle bundle = ResourceBundle.getBundle("db");
2. 获取数据
   String driver = bundle.getString("driver");
   String url = bundle.getString("url");
   String user = bundle.getString("user");
   String password = bundle.getString("password");
3. JDBC访问数据库

Connection conn = null;
Statement stmt = null;
try {
	Class.forName(driver);
    conn = DriverManager.getConnection(url,user,password);
    stmt = conn.createStatement();
    int count = stmt.executeUpdate("insert into dept(deptno,dname,loc) values(50,'program','peking');");
    System.out.println(count == 1? "success":"false");
} catch(SQLException e){
	e.printStackTrace();
} catch(ClassNotFoundException e) {
	e.printStackTrace();	
} finally {
	if(conn != null) {
		try {
			conn.close();
		} catch(SQLException e){
			e.printStackTrace();
	    }
    }
	if(stmt != null) {
		try {
			stmt.close();
		} catch(SQLException e){
			e.printStackTrace();
	    }
    }
 }
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/335189.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号