Performing INSERT Operations in Java with JDBC and MySQL

Java-Database-Connectivity

In this tutorial, we’ll explore how to perform Create, Read, Update, and Delete (CRUD) operations using Java with JDBC (Java Database Connectivity) to interact with a MySQL database. We’ll cover the basics of establishing a database connection, preparing and executing SQL statements, and handling exceptions.

Introduction:

Java Database Connectivity (JDBC) is a Java API that allows Java programs to interact with databases. MySQL is a popular open-source relational database management system. Combining JDBC with MySQL enables Java applications to store and retrieve data from MySQL databases seamlessly.

Prerequisites:

  • Basic knowledge of Java programming language.
  • Installed MySQL Server.
  • MySQL Connector/J library added to your Java project.

Setting Up the Database Connection:

To begin, we establish a connection to the MySQL database using the JDBC driver. The connection parameters such as URL, username, and password are provided as strings.

String url = “jdbc:mysql://localhost:3306/your_database”;
String username = “your_username”;
String password = “your_password”;

 

Performing an SQL INSERT Operation:

Next, let’s perform an SQL INSERT operation to add data to a table. We’ll use parameterized SQL statements to ensure security and prevent SQL injection attacks.

String sql = “INSERT INTO TableName (column1, column2, column3, column4) VALUES (?, ?, ?, ?)”;
String column1Value = “value1”;
String column2Value = “value2”;
String column3Value = “value3”;
String column4Value = “value4”;

try (Connection conn = DriverManager.getConnection(url, username, password);
PreparedStatement pstmt = conn.prepareStatement(sql)) {

pstmt.setString(1, column1Value);
pstmt.setString(2, column2Value);
pstmt.setString(3, column3Value);
pstmt.setString(4, column4Value);

int rowsAffected = pstmt.executeUpdate();
System.out.println(rowsAffected + ” row(s) affected.”);

} catch (SQLException e) {
System.out.println(“Error: ” + e.getMessage());
}

Conclusion:

In this tutorial, we’ve learned how to perform an SQL INSERT operation in Java using JDBC and MySQL. By following similar steps, you can perform other CRUD operations such as SELECT, UPDATE, and DELETE. JDBC provides a powerful and flexible way to interact with databases from Java applications, making it a valuable tool for developers building database-driven applications.

Stay tuned for more tutorials on JDBC and database interaction in Java!

References:

Leave a Reply

Your email address will not be published.Required fields are marked *