Java Database Connectivity (JDBC) is an API that enables Java applications to interact with databases. It provides methods for querying and updating data in a database.
To establish a connection, you need to load the JDBC driver and use the DriverManager to get a connection object.
JDBC allows executing SQL queries using Statement, PreparedStatement, and CallableStatement objects.
import java.sql.*;
public class JDBCExample {
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "user", "password");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM employees");
while (rs.next())
System.out.println(rs.getString(1) + " " + rs.getString(2));
con.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
JDBC operations can throw SQLExceptions, which should be handled using try-catch blocks.
PreparedStatements are used for executing parameterized queries, providing better performance and security.
JDBC supports transaction management, allowing you to commit or rollback transactions based on your requirements.
Console Output:
John Doe
Jane Smith
JDBC batch processing allows you to execute multiple SQL statements as a batch, improving performance.
CallableStatements are used to execute stored procedures in the database.
DatabaseMetaData and ResultSetMetaData provide information about the database and result set respectively.
import java.sql.*;
public class AdvancedJDBC {
public static void main(String[] args) {
try {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "user", "password");
con.setAutoCommit(false);
Statement stmt = con.createStatement();
stmt.addBatch("INSERT INTO employees (name) VALUES ('Alice')");
stmt.addBatch("INSERT INTO employees (name) VALUES ('Bob')");
stmt.executeBatch();
con.commit();
con.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
Savepoints allow you to set intermediate points within a transaction that can be rolled back to if needed.
RowSet is a part of JDBC that provides a way to handle rows of data in a more flexible way than ResultSet.
Connection pooling is a technique used to manage database connections efficiently by reusing them.
Console Output:
Batch executed successfully
Always close JDBC resources like Connection, Statement, and ResultSet to avoid resource leaks.
Use libraries like Apache DBCP or HikariCP for efficient connection pooling.
Write optimized SQL queries to improve performance and reduce load on the database.
import java.sql.*;
public class JDBCBestPractices {
public static void main(String[] args) {
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "user", "password");
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT * FROM employees");
while (rs.next())
System.out.println(rs.getString(1) + " " + rs.getString(2));
} catch (SQLException e) {
System.out.println(e);
} finally {
try { if (rs != null) rs.close(); } catch (SQLException e) { e.printStackTrace(); }
try { if (stmt != null) stmt.close(); } catch (SQLException e) { e.printStackTrace(); }
try { if (con != null) con.close(); } catch (SQLException e) { e.printStackTrace(); }
}
}
}
Cache PreparedStatements to improve performance by reusing them for repeated queries.
Use streaming and pagination techniques to handle large data sets efficiently.
Always validate user inputs and use parameterized queries to prevent SQL injection attacks.
Console Output:
Resources closed successfully
There are four types of JDBC drivers: Type-1 (JDBC-ODBC Bridge), Type-2 (Native API), Type-3 (Network Protocol), and Type-4 (Thin Driver).
Select the appropriate driver based on your application's requirements and the database you are connecting to.
Type-4 drivers are generally preferred for their performance and platform independence.
import java.sql.*;
public class JDBCDriverExample {
public static void main(String[] args) {
try {
// Load the MySQL JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "user", "password");
System.out.println("Connected to the database!");
con.close();
} catch (ClassNotFoundException | SQLException e) {
System.out.println(e);
}
}
}
Ensure the driver version is compatible with your database version to avoid connection issues.
Use Class.forName() to load drivers dynamically at runtime.
Configure driver properties such as timeouts and connection parameters for optimal performance.
Console Output:
Connected to the database!
A transaction is a sequence of operations performed as a single logical unit of work. JDBC provides support for managing transactions.
By default, JDBC connections are in auto-commit mode, meaning each SQL statement is committed immediately after execution.
You can disable auto-commit mode and manually control transactions using commit() and rollback() methods.
import java.sql.*;
public class JDBCTransactionExample {
public static void main(String[] args) {
Connection con = null;
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "user", "password");
con.setAutoCommit(false);
Statement stmt = con.createStatement();
stmt.executeUpdate("UPDATE employees SET salary = salary + 1000 WHERE id = 1");
stmt.executeUpdate("UPDATE employees SET salary = salary - 1000 WHERE id = 2");
con.commit();
System.out.println("Transaction committed successfully.");
} catch (SQLException e) {
System.out.println(e);
try {
if (con != null) con.rollback();
System.out.println("Transaction rolled back.");
} catch (SQLException ex) {
ex.printStackTrace();
}
} finally {
try { if (con != null) con.close(); } catch (SQLException e) { e.printStackTrace(); }
}
}
}
JDBC supports different transaction isolation levels, which define the degree to which the operations in one transaction are isolated from those in other transactions.
Savepoints allow you to rollback a transaction to a specific point without affecting the entire transaction.
Implement strategies to handle deadlocks, such as retrying the transaction or using timeout settings.
Console Output:
Transaction committed successfully.
SQL Injection is a code injection technique that can destroy your database. It is one of the most common web hacking techniques.
Use PreparedStatement or CallableStatement instead of Statement to prevent SQL injection attacks.
Always validate and sanitize user inputs to minimize the risk of SQL injection.
import java.sql.*;
public class SQLInjectionPrevention {
public static void main(String[] args) {
Connection con = null;
PreparedStatement pstmt = null;
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "user", "password");
String query = "SELECT * FROM users WHERE username = ? AND password = ?";
pstmt = con.prepareStatement(query);
pstmt.setString(1, "admin");
pstmt.setString(2, "password123");
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
System.out.println("User authenticated.");
} else {
System.out.println("Invalid credentials.");
}
} catch (SQLException e) {
System.out.println(e);
} finally {
try { if (pstmt != null) pstmt.close(); } catch (SQLException e) { e.printStackTrace(); }
try { if (con != null) con.close(); } catch (SQLException e) { e.printStackTrace(); }
}
}
}
Consider using Object-Relational Mapping (ORM) tools like Hibernate, which inherently protect against SQL injection.
Educate developers about secure coding practices to prevent SQL injection and other vulnerabilities.
Implement monitoring and logging to detect and respond to potential SQL injection attempts.
Console Output:
User authenticated.
Newsletter
Subscribe to our newsletter for weekly updates and promotions.
Wiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterCompany
About usCareersPressCompany
About usCareersPressCompany
About usCareersPressLegal
TermsPrivacyContactAds PoliciesLegal
TermsPrivacyContactAds PoliciesLegal
TermsPrivacyContactAds PoliciesCompany
About usCareersPressCompany
About usCareersPressCompany
About usCareersPressLegal
TermsPrivacyContactAds PoliciesLegal
TermsPrivacyContactAds PoliciesLegal
TermsPrivacyContactAds PoliciesLegal
TermsPrivacyContactAds PoliciesAds Policies