Database program
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DatabaseProgram {
private static final String URL = "jdbc:mysql://localhost:3306/testdb";
private static final String USER = "root"; // Your MySQL username
private static final String PASSWORD = "password"; // Your MySQL password
public static void main(String[] args) {
Connection connection = null;
try {
// Load the JDBC driver (MySQL)
Class.forName("com.mysql.cj.jdbc.Driver");
// Establish the connection
connection = DriverManager.getConnection(URL, USER, PASSWORD);
System.out.println("Connected to the database.");
// Insert a new user
String insertSQL = "INSERT INTO users (name, email) VALUES (?, ?)";
try (PreparedStatement preparedStatement = connection.prepareStatement(insertSQL)) {
preparedStatement.setString(1, "John Doe");
preparedStatement.setString(2, "john.doe@example.com");
int rowsAffected = preparedStatement.executeUpdate();
System.out.println("Inserted " + rowsAffected + " row(s) into the table.");
}
// Query users
String querySQL = "SELECT * FROM users";
try (Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(querySQL)) {
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
String email = resultSet.getString("email");
System.out.println("ID: " + id + ", Name: " + name + ", Email: " + email);
}
}
} catch (ClassNotFoundException e) {
System.err.println("JDBC Driver not found.");
e.printStackTrace();
} catch (SQLException e) {
System.err.println("SQL Exception.");
e.printStackTrace();
} finally {
// Close the connection
if (connection != null) {
try {
connection.close();
System.out.println("Connection closed.");
} catch (SQLException e) {
System.err.println("Failed to close the connection.");
e.printStackTrace();
}
}
}
}
}
Comments
Post a Comment