JDBC(JAVA数据库连接)


try {
    //1.注册驱动
    Class.forName("com.mysql.jdbc.Driver");
    String url = "jdbc:mysql://localhost:3306/mydb?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC ";
    String root = "root";
    String dbpassword = "1234";
    //2.获取连接
    Connection connection = DriverManager.getConnection(url, root, dbpassword);
    //3.获取语句的执行者
    Statement statement = connection.createStatement();
    //4.执行语句
    String sql = "select * from consumer";  //注意:use和user是sql的保留字,如果使用其作为表明,将产生语法错误
    ResultSet resultSet = statement.executeQuery(sql);
    while (resultSet.next()) {
        String id = resultSet.getString(1);     //通过列的索引获取,索引是从1开始
        String username = resultSet.getString("username");  //通过列名值获取
        String password = resultSet.getString(3);
        System.out.println("id: " + id + "  ,username   :" + username + "   ,password:" + password);
    }
    //释放资源
    resultSet.close();
    statement.close();
    connection.close();
} catch (Exception e) {
    e.printStackTrace();
}


另一种,从perproties文件中加载(db.properties在resources文件下——idea)

ResourceBundle bundle = ResourceBundle.getBundle("db/db");
String driver = bundle.getString("jdbc.driver");
String url = bundle.getString("jdbc.url");
username = bundle.getString("jdbc.username");
password = bundle.getString("jdbc.password");
//加载驱动
try {
    Class.forName(driver);
    //2.获取连接
    Connection connection = DriverManager.getConnection(url, username, password);
    return connection;
} catch (Exception e) {
    throw new RuntimeException(e);
}









猜你喜欢

转载自blog.csdn.net/wangjx201212/article/details/80597917