Here’s a sample code snippet that demonstrates how to write data to an Azure SQL Server 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 AzureSQLDataWriter { public static void main(String[] args) { // Database credentials String url = "jdbc:sqlserver://your-server.database.windows.net:1433;databaseName=your-database"; String username = "your-username"; String password = "your-password"; // SQL query String query = "INSERT INTO your-table (name, email) VALUES (?, ?)"; try { // Register JDBC driver Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); // Open a connection Connection conn = DriverManager.getConnection(url, username, password); // Create a prepared statement PreparedStatement stmt = conn.prepareStatement(query); // Set parameter values stmt.setString(1, "John Doe"); stmt.setString(2, "[email protected]"); // Execute the query int rowsAffected = stmt.executeUpdate(); // Process the result System.out.println(rowsAffected + " row(s) inserted successfully."); // Close the resources stmt.close(); conn.close(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } }
Make sure to replace the url
, username
, password
, your-database
, your-table
, and column names with your actual Azure SQL Server connection details and query.
This code snippet assumes you have the Azure SQL Server JDBC driver (e.g., mssql-jdbc.jar
) included in your classpath. If not, you can download it from the official Microsoft website or include it as a Maven/Gradle dependency.
The code connects to the Azure SQL Server database, creates a prepared statement with parameterized values, sets the parameter values using setString()
(or appropriate setter methods), and executes the update query using executeUpdate()
. The method returns the number of rows affected, which can be used for result processing. 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.