The following program demonstrates How to Insert Records in a Database in Java.
To insert a record into a database using Java, you can use JDBC (Java Database Connectivity). JDBC allows you to interact with relational databases. In this example, I’ll show you how to insert a record into a MySQL database, but you can adapt the code to work with other database systems as well.
Before running the program, ensure you have the MySQL JDBC driver (JAR file) included in your project or classpath. You can download it from the official MySQL website or use a build tool like Maven or Gradle to manage dependencies.
Here’s a Java program to insert a record into a MySQL database:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class InsertRecordDemo {
public static void main(String[] args) {
// Database connection parameters
String url = "jdbc:mysql://localhost:3306/mydatabase";
String username = "your_username";
String password = "your_password";
// Data to insert
String name = "John Doe";
int age = 30;
try {
// Establish a database connection
Connection connection = DriverManager.getConnection(url, username, password);
// Create an SQL INSERT statement
String insertSql = "INSERT INTO mytable (name, age) VALUES (?, ?)";
// Create a prepared statement
PreparedStatement preparedStatement = connection.prepareStatement(insertSql);
// Set parameter values
preparedStatement.setString(1, name);
preparedStatement.setInt(2, age);
// Execute the INSERT statement
int rowsInserted = preparedStatement.executeUpdate();
if (rowsInserted > 0) {
System.out.println("Record inserted successfully.");
} else {
System.out.println("No records inserted.");
}
// Close resources
preparedStatement.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Make sure to replace the following placeholders with your own database information:
url
: The JDBC URL of your MySQL database.username
: Your database username.password
: Your database password.
In this program:
- Import the necessary JDBC classes.
- Establish a database connection using
DriverManager.getConnection
. - Create an SQL INSERT statement with placeholders (
?
) for the values to be inserted. - Also, create a
PreparedStatement
to execute the SQL statement. - Set parameter values using
setString
andsetInt
. - Execute the INSERT statement using
executeUpdate
. - Check the number of rows inserted to determine if the operation was successful.
- Close resources (prepared statement and connection) in a
finally
block or using try-with-resources.
Ensure that you have the MySQL database server running and that the specified database and table exist with the appropriate schema.
Further Reading
Spring Framework Practice Problems and Their Solutions
From Google to the World: The Story of Go Programming Language
Why Go? Understanding the Advantages of this Emerging Language
Creating and Executing Simple Programs in Go