Created
March 2, 2015 11:32
-
-
Save revox/c4eaf1808633fc2baa10 to your computer and use it in GitHub Desktop.
JDBC basics, exceptions
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
| import java.sql.*; | |
| public class DBConnectWithExceptions { | |
| public static void main(String[] args) | |
| { | |
| Connection connect = null; | |
| Statement st = null; | |
| try{ | |
| Class.forName("com.mysql.jdbc.Driver"); | |
| connect = DriverManager.getConnection("jdbc:mysql://localhost:8889/java_demo","root","root"); | |
| st = connect.createStatement(); | |
| ResultSet resultSet = st.executeQuery("SELECT * FROM messages"); | |
| while (resultSet.next()) | |
| { | |
| System.out.println(resultSet.getInt("id") + " " | |
| + resultSet.getString("user") + " : " | |
| + resultSet.getString("message")); | |
| } | |
| resultSet.close(); | |
| st.close(); | |
| connect.close(); | |
| } 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(st!=null) | |
| st.close(); | |
| }catch(SQLException se){ | |
| se.printStackTrace(); | |
| } | |
| try{ | |
| if(connect!=null) | |
| connect.close(); | |
| }catch(SQLException se){ | |
| se.printStackTrace(); | |
| }//end finally try | |
| }//end try | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment