Write a Java program to connect to a SQL DataBase.

Category : Java | Sub Category : Java Programs | By Prasad Bonam Last updated: 2021-04-19 09:13:52 Viewed : 725


JDBC is a standard Java API for database-independent connectivity between the Java programming language and a wide range of databases. This application program interface lets you encode the access request statements, in Structured Query Language (SQL). They are then passed to the program that manages the database. It mainly involves opening a connection, creating a SQL Database, executing SQL queries and then arriving at the output. Let’s see an example code to create a database and establish a connection and run the queries.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package runnerdev;
import java.sql.*;
import java.sql.DriverManager;
public class Example {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/emp";
// Database credentials
static final String USER = "root";
static final String PASS = "edureka";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,"root","edureka");
//STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT id, first, last, age FROM Employees";
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");
//Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
//STEP 6: Clean-up environment
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing can be done
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
} // end Example

On executing the above code, it will establish the connection to the database and retrieve the data present in the database.

1
2
3
4
5
6
7
Connecting to database...
Creating statement...
ID: 100, Age: 18, First: Zara, Last: Ali
ID: 101, Age: 25, First: Mahnaz, Last: Fatma
ID: 102, Age: 30, First: Zaid, Last: Khan
ID: 103, Age: 28, First: Sumit, Last: Mittal
Goodbye!

Search
Related Articles

Leave a Comment:
Jose Craig
at 2023-08-30 15:22:23
Greetings If you ever need Negative SEO or a de-rank strategy, you can hire us here https://www.speed-seo.net/product/negative-seo-service/
Marty Bethune
at 2024-03-14 21:57:40
Turn your 5 star reviews into videos that rank super high when people Google your reputation. Pay nothing for the video! Claim your free video now: http://your-top-reviews-to-videos.info
Young Chester
at 2024-03-18 06:45:37
Are you okay running your business without much funds? This could slow down growth and delay returns on your business. Now you have the Opportunity to Fund your Busineses and Projects without stress and without the burden of repayment as our interest in first for the growth of your business and projects, and for your to arrive at your desired business goals and dreams. Take advantage of our Funding opportunity and get funded on your business and Projects within days and have an ample number of years/Loan Term Period which gives you time to grow and achieve your business goals. Give us a call on: +852 3008 8373, or write us at: info@capitalfund-hk.com