How do I query records from table?

Category: java.sql, viewed: 14744 time(s).
package org.kodejava.sample.java.sql;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.ResultSet;

public class ResultSetExample
{
    public static void main(String[] args) throws Exception
    {
        Connection connection = null;
        try
        {
            // Here we load the MySQL database Driver class
            Class.forName("com.mysql.jdbc.Driver");

            // Define properties for connecting to database such as
            // database jdbc url, username and password
            String url = "jdbc:mysql://localhost/sampledb";
            String username = "root";
            String password = "";

            // Get a connection to database.
            connection = DriverManager.getConnection(url, username, password);
            // Create a statment object.
            Statement statement = connection.createStatement();
            // Executes a query command to select isbn and the book title
            // from books table. The execute query returns a ResultSet object
            // which is the result of our query execution.
            ResultSet books = statement.executeQuery("SELECT isbn, title, published_date FROM books");

            // To get the value returned by the statement.executeQuery we need
            // to iterate the books object until the last items.
            while (books.next())
            {
                // To get the value from the ResultSet object we can call
                // a method that correspond to the data type of the column in
                // database table. In the example below we call
                // books.getString("isbn") to get the book's ISBN information.
                System.out.println(books.getString("isbn") + "; "
                        + books.getString("title") + "; "
                        + books.getDate("published_date"));
            }
        } finally {
            if (connection != null && !connection.isClosed())
            {
                // We've done the business with the connection object, so
                // let's close it.
                connection.close();
            }
        }
    }
}
Click here to lend your support to: Kode Java Org and make a donation at www.pledgie.com !

 

Uncensored Newsgroups
Download Hundreds of Complimentary Industry Resources

Get hundreds of popular Industry magazines, white papers, webinars, podcasts, and more; all available at no cost to you. With more than 600 complimentary offers, you'll find plenty of titles to suit your professional interests and needs. Click Here and Sign up today!

Java Training

Sponsored Links

Our Friends

Statistics

Locations of visitors to this page
visitor stats