当前位置:Gxlcms > 数据库问题 > JDBC(1)——获取数据库连接

JDBC(1)——获取数据库连接

时间:2021-07-01 10:21:17 帮助过:22人阅读

1. 准备连接数据库的 4 个字符串. //驱动的全类名. String driverClass = "com.mysql.jdbc.Driver"; //JDBC URL String jdbcUrl = "jdbc:mysql:///test"; //user String user = "root"; //password String password = "1230"; //2. 加载数据库驱动程序(对应的 Driver 实现类中有注册驱动的静态代码块.) Class.forName(driverClass); //3. 通过 DriverManager 的 getConnection() 方法获取数据库连接. Connection connection = DriverManager.getConnection(jdbcUrl, user, password); System.out.println(connection);

进一步进行封装 1)参数提取到文件中

        2)封装到方法里

 

public Connection getConnection() throws Exception{
        //1. 准备连接数据库的 4 个字符串. 
        //1). 创建 Properties 对象
        Properties properties = new Properties();
        
        //2). 获取 jdbc.properties 对应的输入流, src / jdbc.properties
        InputStream in = 
                this.getClass().getClassLoader().getResourceAsStream("jdbc.properties");
        
        //3). 加载 2) 对应的输入流
        properties.load(in);
        
        //4). 具体决定 user, password 等4 个字符串. 
        String user = properties.getProperty("user");
        String password = properties.getProperty("password");
        String jdbcUrl = properties.getProperty("jdbcUrl");
        String driver = properties.getProperty("driver");
        
        //2. 加载数据库驱动程序(对应的 Driver 实现类中有注册驱动的静态代码块.)
        Class.forName(driver);
        
        //3. 通过 DriverManager 的 getConnection() 方法获取数据库连接. 
        return DriverManager.getConnection(jdbcUrl, user, password);
    }

 src / jdbc.properties

#driver=oracle.jdbc.driver.OracleDriver
#jdbcUrl=jdbc:oracle:thin:@localhost:1521:orcl
#user=scott
#password=java

driver=com.mysql.jdbc.Driver
jdbcUrl=jdbc:mysql://localhost:3306/atguigu
user=root
password=1230

 

JDBC(1)——获取数据库连接

标签:管理   color   input   cal   rman   个数   str   实现   bsp   

人气教程排行