Tuesday, September 2, 2008

How to Retrieve data using MySQL in Java Console

This is simple example of data retrieving from the MySQL Database using java code. For connecting mysql database from the java code, you have to add MySQL Connector jar file ( Download MySQL Connector ) in to your reference libraries.

Here's the sample Code....

public class ReadingMySQL

{

    public static void main(String[] args)

   {

          Connection conn = null;
           Statement stmt = null;
            ResultSet rs = null;

            try {
              String dbURL = "jdbc:mysql://localhost:3306/wsasset";   // url of the mysql database
              String username = "root";    // username of  wsasset database
              String password = "";    // password of  wsasset database

               Class.forName("com.mysql.jdbc.Driver");

               conn = DriverManager.getConnection(dbURL, username, password);

               stmt = conn.createStatement();

               if (stmt.execute("select * from assets"))

               {
                     rs = stmt.getResultSet();
                }

               else

               {
                    System.err.println("select failed");
                }
               while (rs.next())

               {
                   String entry = rs.getString(2);
                   System.out.println(entry);
                   System.out.println(rs.getString(3));
                   System.out.println(rs.getString(4));
                   System.out.println(rs.getString(5));
                   System.out.println(rs.getString(6));
                   System.out.println(rs.getString(7));
               }

           } catch (ClassNotFoundException ex)

             {
                  System.err.println("Failed to load mysql driver");
                   System.err.println(ex);
              }

       catch (SQLException ex) {
            System.out.println("SQLException: " + ex.getMessage());
            System.out.println("SQLState: " + ex.getSQLState());
            System.out.println("VendorError: " + ex.getErrorCode());
            }

       finally {
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException ex) { /* ignore */ }
                rs = null;
            }
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException ex) { /* ignore */ }
                stmt = null;
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException ex) { /* ignore */ }
                conn = null;
            }
        }
    }
}

2 comments:

Anonymous said...

thanks

Anonymous said...

i am not able to retrieve the value which are entered using netbean Jframe from my sql database please reply me .