connection to a database
Thu Nov 21 2024 18:05:11 GMT+0000 (Coordinated Universal Time)
Saved by @coding1
SQL CREATE DATABASE sampledb; USE sampledb; CREATE TABLE users ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100), email VARCHAR(100) ); JAVA import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class DatabaseExample { // Database URL, username and password private static final String URL = "jdbc:mysql://localhost:3306/sampledb"; private static final String USERNAME = "your_username"; // Replace with your DB username private static final String PASSWORD = "your_password"; // Replace with your DB password public static void main(String[] args) { Connection connection = null; try { // Establishing the connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD); System.out.println("Connected to the database successfully."); // Inserting data into the users table String insertSQL = "INSERT INTO users (name, email) VALUES (?, ?)"; try (PreparedStatement pstmt = connection.prepareStatement(insertSQL)) { pstmt.setString(1, "John Doe"); pstmt.setString(2, "john@example.com"); pstmt.executeUpdate(); System.out.println("Data inserted successfully."); } // Querying the data String selectSQL = "SELECT * FROM users"; try (PreparedStatement pstmt = connection.prepareStatement(selectSQL); ResultSet rs = pstmt.executeQuery()) { System.out.println("User List:"); while (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("name"); String email = rs.getString("email"); System.out.println("ID: " + id + ", Name: " + name + ", Email: " + email); } } } catch (SQLException e) { System.err.println("SQL Exception: " + e.getMessage()); } finally { // Closing the connection try { if (connection != null && !connection.isClosed()) { connection.close(); System.out.println("Database connection closed."); } } catch (SQLException e) { System.err.println("Failed to close the connection: " + e.getMessage()); } } } }
Comments