Here’s a sample code snippet that demonstrates how to write data to a MySQL database using Java and JDBC (Java Database Connectivity):
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; public class MySQLDataWriter { public static void main(String[] args) { // Database credentials String url = "jdbc:mysql://localhost:3306/mydatabase"; String username = "root"; String password = "password"; // SQL query String query = "INSERT INTO customers (name, email) VALUES (?, ?)"; try { // Register JDBC driver Class.forName("com.mysql.cj.jdbc.Driver"); // Open a connection Connection conn = DriverManager.getConnection(url, username, password); // Create a prepared statement PreparedStatement pstmt = conn.prepareStatement(query); // Set the parameter values pstmt.setString(1, "John Doe"); pstmt.setString(2, "[email protected]"); // Execute the query int rowsAffected = pstmt.executeUpdate(); // Check if the insertion was successful if (rowsAffected > 0) { System.out.println("Data inserted successfully!"); } else { System.out.println("Failed to insert data."); } // Close the resources pstmt.close(); conn.close(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } }
Make sure to replace the url
, username
, and password
variables with your actual MySQL database connection details. Additionally, modify the query
variable to match your desired SQL INSERT statement.
This code snippet assumes you have the MySQL JDBC driver (e.g., mysql-connector-java.jar
) included in your classpath. If not, you can download it from the official MySQL website or include it as a Maven/Gradle dependency.
The code connects to the MySQL database, prepares an INSERT statement with placeholders, sets the parameter values using the setString
method, and executes the query using executeUpdate
. It then checks the number of affected rows to determine if the insertion was successful. Finally, it closes the resources to free up memory.
Remember to handle exceptions appropriately in your production code and consider using try-with-resources or a similar mechanism to automatically close the resources.