将Java连接到MySQL数据库


将Java连接到MySQL数据库

DriverManager是一种相当古老的做事方式。更好的方法是DataSource通过查找已经为您配置的app服务器容器来获取a :

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

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

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

然后从上面获取连接,如上所述:

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