xxxxxxxxxx
import java.sql.*;
public class Main {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydatabase";
String username = "myuser";
String password = "mypassword";
try (Connection conn = DriverManager.getConnection(url, username, password)) {
String sql = "SELECT * FROM users WHERE age > ?";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setInt(1, 18); // Set the value for the placeholder
ResultSet resultSet = statement.executeQuery();
while (resultSet.next()) {
String name = resultSet.getString("name");
int age = resultSet.getInt("age");
System.out.println("Name: " + name + ", Age: " + age);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
xxxxxxxxxx
import java.sql.*;
public class PreparedStatementsExample {
public static void main(String[] args) {
try {
// Establish a connection to the database
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/exampleDB", "username", "password");
// Create a prepared statement
String query = "SELECT * FROM users WHERE age > ?";
PreparedStatement preparedStatement = connection.prepareStatement(query);
// Set parameter values for the prepared statement
int minimumAge = 18;
preparedStatement.setInt(1, minimumAge);
// Execute the prepared statement
ResultSet resultSet = preparedStatement.executeQuery();
// Process the results
while (resultSet.next()) {
String name = resultSet.getString("name");
int age = resultSet.getInt("age");
System.out.println("Name: " + name + ", Age: " + age);
}
// Close the resources
resultSet.close();
preparedStatement.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
xxxxxxxxxx
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class Main {
public static void main(String[] args) {
// Define database URL, username, and password
String url = "jdbc:mysql://localhost:3306/mydatabase";
String username = "root";
String password = "password";
try {
// Establish a connection to the database
Connection connection = DriverManager.getConnection(url, username, password);
// Prepare a SQL statement with parameters
String sql = "INSERT INTO users (name, age) VALUES (?, ?)";
PreparedStatement statement = connection.prepareStatement(sql);
// Set the values for the parameters
statement.setString(1, "John Doe");
statement.setInt(2, 25);
// Execute the SQL statement
int rowsInserted = statement.executeUpdate();
System.out.println(rowsInserted + " row(s) inserted.");
// Close the statement and connection
statement.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}