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,050 points
197 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();
answered May 11, 2018 by parth295
• 4,640 points

Related Questions In Java

0 votes
1 answer

How to connect Java to MySql Database?

This will work: try { ...READ MORE

answered Aug 27 in Java by John
53 views
0 votes
1 answer

How to connect Java to MySql Database?

Make sure you have the MySQL jdbc ...READ MORE

answered Sep 30 in Java by Shyam
36 views
0 votes
1 answer

How to create database in MySql using Java?

First, you will have to create connection ...READ MORE

answered Aug 27 in Java by Juni
33 views
0 votes
1 answer

How to create database in MySql using Java?

First, you will have to create connection ...READ MORE

answered Sep 30 in Java by Shri
27 views
0 votes
1 answer

Is SELECT * harmful in Database?

There are really three major reasons: Inefficiency in ...READ MORE

answered Sep 7, 2018 in Database by DataKing99
• 8,130 points
47 views
0 votes
1 answer

Difference between single and double quotes in SQL

Single quotes are used to indicate the ...READ MORE

answered Sep 11, 2018 in Database by CodingByHeart77
• 3,690 points
88 views
0 votes
1 answer

Can different databases use different name quotes?

This use of quotes is called delimited ...READ MORE

answered Sep 11, 2018 in Database by CodingByHeart77
• 3,690 points
35 views
0 votes
1 answer

Write a SQL query to find the names of employees that begin with ‘S’

To display the name of the employees ...READ MORE

answered Sep 26, 2018 in Database by darklord
• 6,170 points
46 views
0 votes
1 answer

How to calculate the difference between two date instances in Java?

You can use Joda Time Library. Interval i ...READ MORE

answered May 4, 2018 in Java by parth295
• 4,640 points
59 views
0 votes
2 answers

How to read the files using Java?

You can use collections. try (Stream<Path> filePathStream=Files.walk(Paths.get("/home/you/Desktop"))) { ...READ MORE

answered Jul 10, 2018 in Java by Sushmita
• 6,880 points
59 views