Skip to content

Instantly share code, notes, and snippets.

@revox
Created March 2, 2015 11:32
Show Gist options
  • Save revox/c4eaf1808633fc2baa10 to your computer and use it in GitHub Desktop.
Save revox/c4eaf1808633fc2baa10 to your computer and use it in GitHub Desktop.
JDBC basics, exceptions
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