How do I access my MySQL database from Java?

Asked 2 years ago, Updated 2 years ago, 89 views

How do I access my MySQL database from Java?

mysql java jdbc

2022-09-21 18:59

1 Answers

DriverManager is outdated and DataSource is modern.

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

To use it this way or to access the database driver yourself

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

You can do it like this.

And when you connect,

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

You can do it like this.


2022-09-21 18:59

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.