Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package getReq;
- import java.sql.*;
- import com.mysql.jdbc.ResultSet;
- import com.mysql.jdbc.Statement;
- public class DatabaseCon {
- // JDBC driver name and database URL
- static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
- static final String DB_URL = "jdbc:mysql://127.0.0.1:3306/test?useSSL=false";
- // Database credentials
- static final String USER = "root";
- static final String PASS = "qwaszxrc/";
- int id;
- String firstname;
- String lastname;
- String email =null;
- Date reg_date;
- Connection conn = null;
- java.sql.Statement stmt = null;
- public void getConn() {
- try {
- // STEP 2: Register JDBC driver
- Class.forName(JDBC_DRIVER).newInstance();
- // STEP 3: Open a connection
- System.out.println("Connecting to a selected database...");
- conn = DriverManager.getConnection(DB_URL, USER, PASS);
- System.out.println("Connected database successfully...");
- // STEP 4: Execute a query
- System.out.println("Creating statement...");
- stmt = conn.createStatement();
- String sql = "SELECT id, firstname, lastname,email,reg_date FROM MyGuests";
- java.sql.ResultSet rs = stmt.executeQuery(sql);
- // STEP 5: Extract data from result set
- while (rs.next()) {
- // Retrieve by column name
- id = rs.getInt("id");
- firstname = rs.getString("firstname");
- lastname = rs.getString("lastname");
- email = rs.getString("email");
- reg_date = rs.getDate("reg_date");
- // Display values
- System.out.print("ID: " + id);
- System.out.print(",FirstName: " + firstname);
- System.out.print(", LastName: " + lastname);
- System.out.println(", Email: " + email);
- System.out.println(", RegistrationDate is: " + reg_date);
- }
- rs.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 (stmt != null)
- conn.close();
- } catch (SQLException se) {
- } // do nothing
- try {
- if (conn != null)
- conn.close();
- } catch (SQLException se) {
- se.printStackTrace();
- }
- }
- }
- public String getEmail() {
- return email;
- }
- public void setEmail(String email) {
- this.email = email;
- }
- public static void main(String[] args) {
- DatabaseCon testcon = new DatabaseCon();
- testcon.getConn();
- testcon.getEmail();
- System.out.println(testcon.getEmail());
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement