Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
5 views2 pages

JDBC

java data base connection

Uploaded by

chinniz999
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views2 pages

JDBC

java data base connection

Uploaded by

chinniz999
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

import java.sql.

Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

// 1. Load MySQL JDBC Driver (optional in newer versions)


// 2. Establish connection
// 3. Create SQL query using PreparedStatement
// 4. Execute query
// 5. Iterate Reseultset
// 6. Close resources
public class DatabaseExample {

public static void main(String[] args) {


// Database credentials
String jdbcURL = "jdbc:mysql://localhost:3306/testdb";
String username = "root";
String password = "password";

Connection conn = null;


PreparedStatement stmt = null;
ResultSet rs = null;

try {
// 1. Load MySQL JDBC Driver (optional in newer versions)
Class.forName("com.mysql.cj.jdbc.Driver");

// 2. Establish connection
Connection conn = DriverManager.getConnection(jdbcURL, username,
password);
System.out.println("Connected to database!");

// 3. Create SQL query using PreparedStatement


String sql = "SELECT id, name, email FROM users WHERE id = ?";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setInt(1, 1); // Set parameter

// 4. Execute query
rs = stmt.executeQuery();

// 5. Process result
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String email = rs.getString("email");

System.out.println(id + " | " + name + " | " + email);


}

} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
// 6. Close resources
try {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}

You might also like