In this guide, you will learn about the PreparedStatement setString() method in Java programming and how to use it with an example.
1. PreparedStatement setString() Method Overview
Definition:
The setString() method of the PreparedStatement interface is utilized to set the value of the designated parameter with the given Java String value. When it sends it to the database, the driver converts this to an SQL VARCHAR or LONGVARCHAR value.
Syntax:
void setString(int parameterIndex, String x) throws SQLException
Parameters:
- parameterIndex: the first parameter (1-based) specifying the index of the parameter for which the value is to be set.
- x: the Java String value that needs to be set to the designated parameter.
Key Points:
- The setString() method inserts String data into SQL tables.
- The parameterIndex specifies the index of the placeholder in the SQL statement.
- The setString() method can throw an SQLException if the database access error occurs or this method is called on a closed PreparedStatement.
2. PreparedStatement setString() Method Example
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class SetStringExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/ems";
String user = "root";
String password = "root"; // replace your database password
String sql = "INSERT INTO employees (first_name, last_name) VALUES (?, ?)";
try (Connection connection = DriverManager.getConnection(url, user, password);
PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
// Using setString() to set values for the placeholders
preparedStatement.setString(1, "John");
preparedStatement.setString(2, "Doe");
int rowsAffected = preparedStatement.executeUpdate();
System.out.println("Rows affected: " + rowsAffected);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Output:
Rows affected: 1
Explanation:
In the above example, we connect to a database and use the setString() method to insert a new row into the employees table.
The setString() method sets the values for the first_name and last_name columns. After executing the update, the program prints the number of affected rows, indicating the successful insertion of the new employee data.
Comments
Post a Comment
Leave Comment