What is JDBC?
JDBC stands for Java Database Connectivity, is a set of Java API for accessing the relational databases from Java program. The Java API enables the programmers to execute the SQL statements against the JDBC complaint database.
JDBC allows the programmers to quickly develop small Java applications that interact with the databases.
To develop an application programmer has to:
- Develop the code to connect to the database
- Write the code to execute the query.
Once the query is successfully executed and result is retrieved from the database, programmer can read the data programmatically from the result set object.
How dose it Work ?
you will find the steps below sorted in steps :
- Load the Driver class.
- Create the connection using the static getConnection method
- Create a Statement class to execute the SQL statement
- Execute the SQL statement and get the results in a Resultset
- Iterate through the ResultSet,
Code Example:
- // Change the connection string according to your db, ip, username and password
- String connectionURL = "jdbc:postgresql://localhost:5432/movies;user=java;password=samples";
- try {
- // 1_ Load the Driver class.
- Class.forName("org.postgresql.Driver");
- // If you are using any other database then load the right driver here.
- // 2_ Create the connection using the static getConnection method
- Connection con = DriverManager.getConnection (connectionURL);
- //3_ Create a Statement class to execute the SQL statement
- Statement stmt = con.createStatement();
- //4_ Execute the SQL statement and get the results in a Resultset
- ResultSet rs = stmd.executeQuery("select * from table ");
- // 5 _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();
- }
No comments:
Post a Comment