jdbc连接mysql,将需要的信息配置到文件中
package com.examples.jdbc.o4_配置连接信息;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ResourceBundle;
/*
将连接数据库所需要的信息全部写到配置文件中
*/
public class Test {
public static void main(String[] args) {
resourceBundle();
}
//通过资源绑定器绑定属性配置文件
public static void resourceBundle(){
//获取指定配置文件的资源绑定器
ResourceBundle resourceBundle = ResourceBundle.getBundle("config/jdbc");
String driver = resourceBundle.getString("driver");
String url = resourceBundle.getString("url");
String userName = resourceBundle.getString("userName");
String passWord = resourceBundle.getString("passWord");
Connection connection = null;
Statement statement = null;
try {
//1.(常用注册驱动的方法)
Class.forName(driver);
//2.
connection = DriverManager.getConnection(url, userName, passWord);
//3.
statement = connection.createStatement();
//4.
String sql = "update student set sname = '郭郭' where sname = 'wangxun'";
int num = statement.executeUpdate(sql);
System.out.println(num == 1 ? "修改成功" : "修改失败");
//5.
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}finally {
//6.
if(statement != null){
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(connection != null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
配置文件的信息
文件名:jdbc.properties
文件内容
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://ip/数据库名
userName=用户名
passWord=密码
相关文章
暂无评论...