How to connect Java program to the MySQL database

0 votes
I am working on JDBC. But I got stuck in connectivity. I have created MySQL database. How can I connect my Java code to database?
May 11, 2018 in Java by Daisy
• 8,140 points
• 4,029 views

1 answer to this question.

0 votes

You can connect your Java code with MySQL database using Connection interface and DriverManager class.

Connection con=DriverManager.getConnection( 

"jdbc:mysql://localhost:3306/Database_name?autoReconnect=true&useSSL=false",“username","password"); 

Or you can use DataSource.

Context context = new InitialContext();
DataSource dataSource = (DataSource) context.lookup("java:comp/env/jdbc/myDB");
MysqlDataSource dataSource = new MysqlDataSource();
dataSource.setUser("user_name");
dataSource.setPassword("password");
dataSource.setServerName("Server_name");
Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM USERS");
...
rs.close();
stmt.close();
conn.close();

Hope this helps!

Check out Java training online to become certified expert.

Thanks!