且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将 Java 连接到 MySQL 数据库

更新时间:2022-06-15 09:24:05

DriverManager 是一种相当古老的做事方式.更好的方法是获取 DataSource,或者通过查找您的应用服务器容器已经为您配置的:

DriverManager is a fairly old way of doing things. The better way is to get a DataSource, either by looking one up that your app server container already configured for you:

Context context = new InitialContext();
DataSource dataSource = (DataSource) context.lookup("java:comp/env/jdbc/myDB");

或直接从您的数据库驱动程序实例化和配置一个:

or instantiating and configuring one from your database driver directly:

MysqlDataSource dataSource = new MysqlDataSource();
dataSource.setUser("scott");
dataSource.setPassword("tiger");
dataSource.setServerName("myDBHost.example.org");

然后从中获取连接,同上:

and then obtain connections from it, same as above:

Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT ID FROM USERS");
...
rs.close();
stmt.close();
conn.close();