JDBC连接到数据库

  1. 硬编码
   public static void main(String[] args) throws SQLException {
        String url = "jdbc:mysql://localhost:3306/test";
        String user = "root";
        String password = "123456";
        //打开一个数据库连接。驱动管理器遍历所有注册过的驱动程序,以便找到一个能够使用数据库URL中指定的子协议的驱动程序。
        //getConnection()方法返回一个与数据库连接的连接对象。
        Connection connection = DriverManager.getConnection(url, user, password);
    }

调试JDBC相关的问题,可以启用JDBC跟踪特性调用DriverManager.setLogWritter方法,可以将跟踪信息发送给PrintWriter,而PrintWriter将输出JDBC活动的详细列表。也可以添加到URL选项中。

  1. 使用配置文件
    配置文件放在项目根目录下,配置如下:
### database.properties
jdbc.drivers=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/jd
jdbc.username=root
jdbc.password=123456
 public static void main(String[] args) throws IOException {
        try {
            runTest();
        } catch (SQLException e) {
            for (Throwable t : e) {
                t.printStackTrace();
            }
        }
    }

    public static void runTest() throws SQLException, IOException {
        try (Connection conn = getConnection();
             Statement stat = conn.createStatement()) {
            stat.execute("CREATE TABLE Greetings (Message varchar(22))");
            stat.execute("INSERT INTO Greetings Values('hello world')");
            try (ResultSet resultSet = stat.executeQuery("SELECT * FROM Greetings")) {
                if (resultSet.next()) {
                    System.out.println(resultSet.getString(1));
                }
            }
            stat.executeUpdate("Drop table Greetings");
        }
    }

    /**
     * 从指定的database.properties文件中获取连接
     *
     * @return
     */
    public static Connection getConnection() throws IOException, SQLException {
        Properties props = new Properties();
        try (InputStream in = Files.newInputStream(Paths.get("database.properties"))) {
            props.load(in);
        }

        String drivers = props.getProperty("jdbc.drivers");
        if (drivers != null) {
            System.setProperty("jdbc.drivers", drivers);
        }
        String url = props.getProperty("jdbc.url");
        String username = props.getProperty("jdbc.username");
        String password = props.getProperty("jdbc.password");
        Connection connection = DriverManager.getConnection(url, username, password);
        return connection;
    }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容