A simple JDBC application sample code

By: Ramlak Emailed: 1729 times Printed: 2338 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

The basic process for a single data retrieval operation using JDBC would be as follows.

  • a JDBC driver would be loaded;
  • a database Connection object would be created from using the DriverManager (using the database driver loaded in the first step);
  • a Statement object would be created using the Connection object;
  • a SQL Select statement would be executed using the Statement object, and a ResultSet would be returned;
  • the ResultSet would be used to step through (or iterate through) the rows returned and examine the data.

The following JDBC code sample demonstrates this sequence of calls.

JDBCSample.java

import java.sql.*;
 
public class JDBCSample {
 
public static void main( String args[]) {
 
String connectionURL = "jdbc:postgresql://localhost:5432/movies;user=java;password=samples";
// Change the connection string according to your db, ip, username and password
 
try {
 
    // Load the Driver class.
    Class.forName("org.postgresql.Driver");
    // If you are using any other database then load the right driver here.
 
    //Create the connection using the static getConnection method
    Connection con = DriverManager.getConnection (connectionURL);
 
    //Create a Statement class to execute the SQL statement
    Statement stmt = con.createStatement();
 
    //Execute the SQL statement and get the results in a Resultset
    ResultSet rs = stmt.executeQuery("select moviename, releasedate from movies");
 
    // Iterate through the ResultSet, displaying two values
    // for each row using the getString method
 
    while (rs.next())
        System.out.println("Name= " + rs.getString("moviename") + " Date= " + rs.getString("releasedate"));
}
catch (SQLException e) {
    e.printStackTrace();
}
catch (Exception e) {
    e.printStackTrace();
}
finally {
    // Close the connection
    con.close();
}
}
}

JDBC Home | All JDBC Tutorials | Latest JDBC Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(21)


1. View Comment

Thnx Ramlak,but be ware about syntax errors.

View Tutorial          By: Saber at 2008-11-03 07:45:23
2. View Comment

Simple and effective example

View Tutorial          By: Anand at 2009-02-05 00:18:10
3. View Comment

Thanks it helped to understand but error occurred

View Tutorial          By: Maya at 2010-11-17 22:08:10
4. View Comment

nice one to understand the basic steps of jdbc....

View Tutorial          By: trishna at 2011-06-10 00:04:21
5. View Comment

In line No. 23, change stmd to stmt.
ResultSet rs = stmd.executeQuery("select moviename, releasedate from movies"); //wrong

ResultSet rs = stmt.executeQuery("select moviename, releasedate from movies"); //right


View Tutorial          By: Rishi Raj at 2011-07-08 13:50:11
6. View Comment

Sir. Please give an example which is small and understand by java beginer like me. Please i want it .im nt able to undstand above one. Gd night.

View Tutorial          By: Rafik at 2011-08-17 19:45:04
7. View Comment

sir, am doing my mca project in java based on network security, i need some java codings ,help me.

View Tutorial          By: saravanapriya at 2011-11-24 03:25:06
8. View Comment

sir i need some simple example of jdbc i cannot understand this

View Tutorial          By: sumit at 2011-11-26 18:02:14
9. View Comment

Sir. Please give an example which is small and understand by java program. Please i want it .am not able to understand above one. and basic knowledge of java to me? thank you

View Tutorial          By: mogesie gedamu at 2011-12-19 12:55:33
10. View Comment

Thank for simple and nice code. Pls,
1. line 8 "Change the connection string according to your db". How can I get the string to my DB?

2. line 14 "If you are using any other database then load the right driver here", how also I can know the right driver?

Thanks


View Tutorial          By: Sherif at 2011-12-26 14:12:12
11. View Comment

Your program contains only data retrieval command.Use of Data Manipulation Command may enhance your program.

View Tutorial          By: Govindarajan at 2012-02-08 01:02:01
12. View Comment

Sir, I need to use MS Access as a database in java. My doubt is, whether I need to connect the database again and again whenever my system restarts??? any simple way to make my database is always connected???

View Tutorial          By: John Moses at 2012-03-31 00:20:38
13. View Comment

Thanks sir i am understand to jdbc but who will run this program on MS-dos. please give me provide to whose command? immiadetly sir..

View Tutorial          By: Ranjeet singh at 2012-05-04 07:40:29
14. View Comment

my question is how do this program connect to my sql 5.5?
and eclipse and netbeans?


View Tutorial          By: ravisskit at 2012-10-08 12:00:18
15. View Comment

one closing bracket ')' is required at while loop in printing statement.

View Tutorial          By: varsha Tambe at 2013-01-07 09:34:37
16. View Comment

It is very help full to me and very simple understandable program Method then comments are great help to myself. I really Thank you.
Regards,
Reddymalla Babu Sircilla.


View Tutorial          By: Reddymalla Babu Sircilla at 2013-02-22 08:28:22
17. View Comment

wt about line of 35 {e.printStackTrace();} i don't know plz tell me abt yhis line

Regards,
Reddymalla babu Sircilla


View Tutorial          By: Reddymalla Babu Sircilla at 2013-02-22 08:38:30
18. View Comment

semicolon(*;) is missed in first line..con .close() method is not possible for this program

Regards,
Reddymalla babu Sircilla


View Tutorial          By: Reddymalla Babu Sircilla at 2013-02-22 09:01:29
19. View Comment

This is very simple code and very much understandable. Exclusively try, catch block is easy to program...

Can you please send me these kind of program like validation(throwing error in GUI) with database.

Thanks!


View Tutorial          By: Prem Anand at 2013-05-04 11:21:16
20. View Comment

sir i need some simple example of jdbc i cannot understand this..

View Tutorial          By: Velkumar.s at 2013-05-15 07:08:37
21. View Comment

this code runs permanently!!! created by diko(Turkey)

public void mysql() {

try {
Class.forName(“com.mysql.jdbc.Driver”);
} catch (ClassNotFoundException e) {
e.printStackTrace();

}

thrd1 = new Thread(new Runnable() {
public void run() {
while (!Thread.interrupted()) {
try {
Thread.sleep(100);
} catch (InterruptedException e1) {

}
if (con == null) {
try {
con = DriverManager.getConnection(“jdbc:mysql://192.168.1.45:3306/deneme”, “ali”, “12345″);

} catch (SQLException e) {
e.printStackTrace();
con = null;
}

if ((thrd2 != null) && (!thrd2.isAlive()))
thrd2.start();

}
}

}
});
if ((thrd1 != null) && (!thrd1.isAlive())) thrd1.start();

thrd2 = new Thread(new Runnable() {
public void run() {
while (!Thread.interrupted()) {

if (con != null) {
try {
// con = DriverManager.getConnection(“jdbc:mysql://192.168.1.45:3306/deneme”, “ali”, “12345″);
Statement st = con.createStatement();
String ali = “‘fff’”;
st.execute(“INSERT INTO deneme (name) VALUES(” + ali + “)”);
// ResultSet rs = st.executeQuery(“select * from deneme”);
// ResultSetMetaData rsmd = rs.getMetaData();
// String result = new String();

// while (rs.next()) {
// result += rsmd.getColumnName(1) + “: ” + rs.getInt(1) + “\n”;
// result += rsmd.getColumnName(2) + “: ” + rs.getString(2) + “\n”;

// }

} catch (SQLException e) {
e.printStackTrace();
con = null;
}

try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

});

}


View Tutorial          By: ali at 2013-08-12 07:56:01

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Ramlak
While Loop in VB.net
For Each…Next Loop in VB.net
For Loop in VB.net
Do Loop in VB.net
Setting Up SSL on Tomcat
Unicode and UTF-8 in C
Sample program to demonstrate the use of ActionListener
java.io.IOException: HTTPS hostname wrong: should be
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
NotifyUtil::java.net.ConnectException: Connection refused: connect
'LINK.EXE' is not recognized as an internal or ext
Using Transactions in JDBC
What is the ACID principal?
How connection pooling works in Java and JDBC
A simple JDBC application sample code

More Tutorials in JDBC
TEXT datatype SPLIT in MSSQL - to solve the 8000 limit set by varchar
Import TEXT to TABLE in MSSQL
What is Referential Integrity in databases?
Handling CSV in Stored Procedures
setSavepoint and releaseSavepoint Example in Java
Calling a Stored Procedure from JDBC in Java
java.lang.NoClassDefFoundError and java.lang.NoSuchMethodError
Creating Database Connection Pool in Tomcat 5.0 and Tomcat 5.5 for MySQL and Java
JDBC Basics and JDBC Components
SELECT Statements
WHERE Clauses in SQL
Joins example in SQL
Common SQL Commands
Result Sets, Cursors and Transactions in SQL
Stored Procedures example in SQL

More Latest News
Most Viewed Articles (in JDBC )
How connection pooling works in Java and JDBC
A simple JDBC application sample code
Using JDBC to extract data from a database and output to an XML document
What is JDBC?
JDBC Architecture
Using the DriverManager Class vs Using a DataSource Object for a connection
Calling a Stored Procedure from JDBC in Java
Using JDBC to connect to MySQL from Java Program
Creating Database Connection Pool in Tomcat 5.0 and Tomcat 5.5 for MySQL and Java
java.lang.NoClassDefFoundError and java.lang.NoSuchMethodError
The Structure of JDBC
What is the ACID principal?
Using Transactions in JDBC
Data Access Technologies in Java
JDBC and Tomcat context settings
Most Emailed Articles (in JDBC)
How connection pooling works in Java and JDBC
WHERE Clauses in SQL
JDBC Architecture
Using Transactions in JDBC
Creating Database Connection Pool in Tomcat 5.0 and Tomcat 5.5 for MySQL and Java
setSavepoint and releaseSavepoint Example in Java
TEXT datatype SPLIT in MSSQL - to solve the 8000 limit set by varchar
What is JDBC?
The Structure of JDBC
A simple JDBC application sample code
What is the ACID principal?
JDBC and Tomcat context settings
SELECT Statements
Joins example in SQL
Common SQL Commands