Advertisement
Guest User

javadio

a guest
Jan 23rd, 2017
159
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.71 KB | None | 0 0
  1. import java.sql.Connection;
  2. import java.sql.DriverManager;
  3. import java.sql.ResultSet;
  4. import java.sql.SQLException;
  5. import java.sql.Statement;
  6.  
  7. public class JBDC
  8. {
  9.     private Connection connection =null;
  10.    
  11.     public void connect()
  12.     {
  13.         String dbname = "Gym";
  14.         String username = "postgres";
  15.         String password = "199292";
  16.        
  17.         try
  18.         {
  19.         connection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/" + dbname,username, password);
  20.         }
  21.         catch (SQLException e) {
  22.         System.err.println("Connection Failed!"); e.printStackTrace();
  23.         return;
  24.         }
  25.         if (connection != null) {
  26.         System.out.println("Connection successful"); } else
  27.         { }
  28.         System.err.println("Failed to make connection!");
  29.        
  30.     }
  31.    
  32.     public void close()
  33.     {
  34.         try
  35.         {
  36.         connection.close(); System.out.println("Connection closed");
  37.         }
  38.         catch (SQLException e) {
  39.                             e.printStackTrace();
  40.         System.out.println("Connection could not be closed – SQL exception");
  41.         }
  42.     }
  43.    
  44.     public void executeQuery ()
  45.     {
  46.         Statement stmt = null;
  47.         String query = " SELECT * FROM course";
  48.         try {
  49.         stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery(query);
  50.         //the next method of ResultSet allows you to iterate through the results
  51.         while (rs.next())
  52.         {
  53.         // the getString method of the ResultSet object allows you to access the value for the given column name for the current row in the result set as a String. If the value is an integer you can use getInt(“col_name”)
  54.                                   String course_name = rs.getString("name");
  55.         System.out.println(course_name); }
  56.         }
  57.         catch (SQLException e ) {
  58.         e.printStackTrace();
  59.         System.err.println("error executing query " + query);
  60.         }
  61.     }
  62.    
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement