Sample Program 1
import [Link].*;
public class JDBCConnectivity {
public static void main(String[] args) {
// Database URL, username, and password
String url = "jdbc:mysql://localhost:3306/testdb"; // Change 'testdb' to your database name
String user = "root"; // Change to your MySQL username
String password = "password"; // Change to your MySQL password
// JDBC variables
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
// Load MySQL JDBC Driver
[Link]("[Link]");
// Establish connection
conn = [Link](url, user, password);
[Link]("Connected to the database successfully!");
// Create a statement object
stmt = [Link]();
// Create a table (if not exists)
String createTableSQL = "CREATE TABLE IF NOT EXISTS Users (id INT PRIMARY KEY
AUTO_INCREMENT, name VARCHAR(50), age INT)";
[Link](createTableSQL);
[Link]("Table created or already exists.");
// Insert a record
String insertSQL = "INSERT INTO Users (name, age) VALUES ('John Doe', 30)";
[Link](insertSQL);
[Link]("Record inserted successfully.");
// Retrieve and display data
String selectSQL = "SELECT * FROM Users";
rs = [Link](selectSQL);
[Link]("User Data:");
while ([Link]()) {
[Link]("ID: " + [Link]("id") + ", Name: " + [Link]("name") + ", Age: "
+ [Link]("age"));
} catch (Exception e) {
[Link]();
} finally {
try {
if (rs != null) [Link]();
if (stmt != null) [Link]();
if (conn != null) [Link]();
} catch (SQLException e) {
[Link]();
Sample Program 2
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class JDBCDemo {
public static void main(String[] args) {
// Database credentials
String url = "jdbc:mysql://localhost:3306/your_database"; // Change 'your_database'
String user = "root"; // Change to your MySQL username
String password = "your_password"; // Change to your MySQL password
Connection conn = null;
Statement stmt = null;
try {
// Step 1: Load MySQL JDBC Driver
[Link]("[Link]");
// Step 2: Establish the connection
conn = [Link](url, user, password);
// Step 3: Create and execute SQL statement
stmt = [Link]();
String query = "SELECT * FROM your_table"; // Change 'your_table'
ResultSet rs = [Link](query);
// Step 4: Process the result set
while ([Link]()) {
int id = [Link]("id");
String name = [Link]("name");
[Link]("ID: " + id + ", Name: " + name);
// Step 5: Close resources
[Link]();
[Link]();
[Link]();
} catch (ClassNotFoundException e) {
[Link]("JDBC Driver not found!");
[Link]();
} catch (SQLException e) {
[Link]("Database connection error!");
[Link]();
} finally {
try {
if (stmt != null) [Link]();
if (conn != null) [Link]();
} catch (SQLException e) {
[Link]();
}
Links for installation:
JDBC Connection
[Link]
MYSQL Installation
[Link]
[Link]
Mysql connection with Eclipse
[Link]
[Link]
Mysql with Netbeans
[Link]
[Link]