Here is a sample code to connect to a MySQL database
Database name : yourdatabase
Databse user : aUser
Database password : aPwd
import java.sql.*;
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try{
Class.forName(com.mysql.jdbc.Driver);
conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/yourdatabase",aUser,aPwd);
//Create a Statement object.
stmt = conn.createStatement();
//Get a ResultSet
rs = stmt.executeQuery("select * from users");
//Loop through the results
while(rs.next()){
String userName = rs.getString("user");
System.out.println(userName );
}
}catch( Throwable t){
//handle error here
t.printStackTrace();
}
finally{
//note the sequence of closing the objects. rs first
// followed by stmt and connection
try{
if(rs != null) rs.close();
}catch(Throwable t){t.printStackTrace();}
try{
if(stmt != null) stmt.close();
}catch(Throwable t){t.printStackTrace();}
try{
if(con != null) con.close();
}catch(Throwable t){t.printStackTrace();}
}
Always remember to close your objects in a finally block. That is the time tested best practice.
Hope this helps!
Sincerely, your friends at JavaAdvice.com