Created
July 13, 2014 09:08
-
-
Save mh-github/37783fa2c65503135f9e to your computer and use it in GitHub Desktop.
Fetch records from MySQL and print them
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //STEP 1. Import required packages | |
| import java.sql.*; | |
| public class MySQL_Fetch | |
| { | |
| // JDBC driver name and database URL | |
| static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; | |
| static final String DB_URL = "jdbc:mysql://localhost/test"; | |
| // Database credentials | |
| static final String USER = "root"; | |
| static final String PASS = "root"; | |
| public static void main(String[] args) | |
| { | |
| Connection conn = null; | |
| Statement stmt = null; | |
| try { | |
| // STEP 2: Register JDBC driver | |
| Class.forName("com.mysql.jdbc.Driver"); | |
| // STEP 3: Open a connection | |
| System.out.println("Connecting to test database..."); | |
| conn = DriverManager.getConnection(DB_URL, USER, PASS); | |
| System.out.println("Connected database successfully..."); | |
| // STEP 4: Execute a query | |
| System.out.println("Fetching records from the table..."); | |
| stmt = conn.createStatement(); | |
| long time1 = System.currentTimeMillis(); | |
| // Fetch twenty thousand records and print them | |
| String sql = "SELECT * FROM seq"; | |
| ResultSet rs = stmt.executeQuery(sql); | |
| // Extract data from result set | |
| int id; | |
| String seq; | |
| while (rs.next()){ | |
| // Retrieve by column name | |
| id = rs.getInt("idseq"); | |
| seq = rs.getString("seqcol"); | |
| // Print record | |
| System.out.println("id: " + id + " seq " + seq); | |
| } | |
| rs.close(); | |
| long time2 = System.currentTimeMillis(); | |
| // Print time | |
| System.out.println("------------------"); | |
| System.out.println("Fetched and printed 20000 records from the table..."); | |
| System.out.println("Time taken = " + (time2 - time1) + " ms"); | |
| } | |
| 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) | |
| conn.close(); | |
| } | |
| catch (SQLException se) { | |
| } // do nothing | |
| try { | |
| if (conn!=null) | |
| conn.close(); | |
| } | |
| catch (SQLException se) { | |
| se.printStackTrace(); | |
| } //end finally try | |
| } //end try | |
| System.out.println("Goodbye!"); | |
| } // end main | |
| } // end MySQL_Fetch |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment