Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.sql.Statement;
- public class JBDC
- {
- private Connection connection =null;
- public void connect()
- {
- String dbname = "Gym";
- String username = "postgres";
- String password = "199292";
- try
- {
- connection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/" + dbname,username, password);
- }
- catch (SQLException e) {
- System.err.println("Connection Failed!"); e.printStackTrace();
- return;
- }
- if (connection != null) {
- System.out.println("Connection successful"); } else
- { }
- System.err.println("Failed to make connection!");
- }
- public void close()
- {
- try
- {
- connection.close(); System.out.println("Connection closed");
- }
- catch (SQLException e) {
- e.printStackTrace();
- System.out.println("Connection could not be closed – SQL exception");
- }
- }
- public void executeQuery ()
- {
- Statement stmt = null;
- String query = " SELECT * FROM course";
- try {
- stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery(query);
- //the next method of ResultSet allows you to iterate through the results
- while (rs.next())
- {
- // 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”)
- String course_name = rs.getString("name");
- System.out.println(course_name); }
- }
- catch (SQLException e ) {
- e.printStackTrace();
- System.err.println("error executing query " + query);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement