View Single Post
  #7 (permalink)  
Old 01-24-2008, 09:46 PM
JAdmin JAdmin is offline
Member
 
Join Date: Jan 2008
Posts: 20
JAdmin is on a distinguished road
Here is a sample code to connect to a MySQL database

Code:
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

Last edited by JAdmin : 01-25-2008 at 02:06 AM.
Reply With Quote