Created
December 17, 2018 14:32
-
-
Save h-hub/0982b563b1144a40cbf2adf0ace55645 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package javaPractice.jdbc; | |
//Import required packages | |
import java.sql.Connection; | |
import java.sql.DriverManager; | |
import java.sql.ResultSet; | |
import java.sql.SQLException; | |
import java.sql.Statement; | |
public class JdbcExample { | |
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; | |
static final String DB_URL = "jdbc:mysql://localhost:3306/cms_crud?useSSL=false"; | |
static final String USER = "root"; | |
static final String PASS = "admin1234"; | |
public static void main(String[] args) { | |
Connection conn = null; | |
Statement stmt = null; | |
try { | |
// Register JDBC driver | |
Class.forName("com.mysql.jdbc.Driver"); | |
System.out.println("Connecting to database..."); | |
// Open a connection | |
conn = DriverManager.getConnection(DB_URL, USER, PASS); | |
// Execute a query | |
System.out.println("Creating statement..."); | |
stmt = conn.createStatement(); | |
String sql = "SELECT ID, FIRST_NAME, LAST_NAME, EMAIL FROM USER"; | |
ResultSet rs = stmt.executeQuery(sql); | |
// Extract data from result set | |
while (rs.next()) { | |
// Retrieve by column name | |
int id = rs.getInt("ID"); | |
String first = rs.getString("FIRST_NAME"); | |
String last = rs.getString("LAST_NAME"); | |
String email = rs.getString("EMAIL"); | |
// Display values | |
System.out.print("ID: " + id); | |
System.out.print(", First: " + first); | |
System.out.print(", Last: " + last); | |
System.out.println(", Email: " + email); | |
} | |
// Clean-up environment | |
rs.close(); | |
stmt.close(); | |
conn.close(); | |
} catch (SQLException | ClassNotFoundException se) { | |
// Handle errors for JDBC | |
se.printStackTrace(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment