Skip to content

Commit

Permalink
Fixes #516 - Fix 'Create a SQL command line' example (#531)
Browse files Browse the repository at this point in the history
  • Loading branch information
mnriem authored Jan 17, 2025
1 parent d26d94c commit 4b002df
Show file tree
Hide file tree
Showing 7 changed files with 139 additions and 61 deletions.
29 changes: 19 additions & 10 deletions sql/get-country/README.md → sql/cli/README.md
Original file line number Diff line number Diff line change
@@ -1,29 +1,27 @@

# Get country information (JDBC client)
# SQL Database JDBC CLI

[![sql/get-country/README.md](https://github.com/Azure-Samples/java-on-azure-examples/actions/workflows/sql_get-country_README_md.yml/badge.svg)](https://github.com/Azure-Samples/java-on-azure-examples/actions/workflows/sql_get-country_README_md.yml)

## Prerequisites

<!-- workflow.cron(0 6 * * 1) -->
<!-- workflow.include(../load-your-mssql-database-with-data/README.md) -->
<!-- workflow.include(../open-firewall-to-your-ip/README.md) -->

This example assumes you have previously completed the following examples:

1. [Create an Azure Resource Group](../../group/create/README.md)
1. [Create an Azure SQL Database](../create/README.md)
1. [Install curl](https://curl.haxx.se/download.html)
1. [Open Azure SQL server firewall to your IP address](../open-firewall-to-your-ip/README.md)
1. [Install mssql-cli client](https://docs.microsoft.com/en-us/sql/tools/mssql-cli?view=sql-server-ver15)
1. [Load your Azure SQL database with your data](../load-your-mssql-database-with-data/README.md)

## Get country information
## SQL Database JDBC CLI

This example will get country information from the database.
This example will send a SQL statement to the database.

<!-- workflow.run()
cd sql/get-country
cd sql/cli
-->

Expand All @@ -33,11 +31,22 @@ First lets build the example.
mvn package
```

The command line below will get the country information for the country with
the abbreviation 'USA'.
Setup the correct environment variables.

```shell
java -jar target/get-country.jar "jdbc:sqlserver://$MSSQL_DNS_NAME:1433;databaseName=demo;encrypt=true;trustServerCertificate=true" $MSSQL_CLIENT_USERNAME $MSSQL_PASSWORD USA
export MSSQL_DNS_NAME=`az sql server show \
--resource-group $RESOURCE_GROUP \
--name $MSSQL_NAME \
--query fullyQualifiedDomainName \
--output tsv`

export MSSQL_CLIENT_USERNAME="$MSSQL_USERNAME@$MSSQL_NAME"
```

The command line below will send the "SELECT 1" statement to the database.

```shell
java -jar target/cli.jar "jdbc:sqlserver://$MSSQL_DNS_NAME:1433;encrypt=true;trustServerCertificate=true" $MSSQL_CLIENT_USERNAME $MSSQL_PASSWORD "SELECT 1"
```

<!-- workflow.run()
Expand Down
43 changes: 21 additions & 22 deletions sql/get-country/pom.xml → sql/cli/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>examples.azure.sql</groupId>
<artifactId>sql-get-country</artifactId>
<artifactId>cli</artifactId>
<version>1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>MSSQL JDBC command line client</name>
<name>MSSQL JDBC CLI</name>
<properties>
<!-- dependencies -->
<mssql-jdbc.version>12.6.1.jre11</mssql-jdbc.version>
Expand All @@ -19,7 +19,7 @@
<maven-jar-plugin.version>3.3.0</maven-jar-plugin.version>
</properties>
<build>
<finalName>get-country</finalName>
<finalName>cli</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
Expand All @@ -31,35 +31,34 @@
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>${maven-dependency-plugin.version}</version>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.4</version>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
<goal>shade</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/lib</outputDirectory>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>examples.azure.mssql.cli.Cli</mainClass>
</transformer>
</transformers>
<filters>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/*.SF</exclude>
<exclude>META-INF/*.DSA</exclude>
<exclude>META-INF/*.RSA</exclude>
</excludes>
</filter>
</filters>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>${maven-jar-plugin.version}</version>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<classpathPrefix>lib/</classpathPrefix>
<mainClass>examples.azure.mssql.getcountry.GetCountry</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
Expand Down
95 changes: 95 additions & 0 deletions sql/cli/src/main/java/examples/azure/mssql/cli/Cli.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
package examples.azure.mssql.cli;

import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Cli {

private Connection connection;
private String[] arguments;

public Cli(String[] arguments) throws SQLException {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
} catch (ClassNotFoundException e) {
throw new SQLException("SQLServerDriver not found", e);
}
String url = arguments[0];
if (!url.startsWith("jdbc:")) {
url = "jdbc:sqlserver://" + url;
}
this.connection = DriverManager.getConnection(url, arguments[1], arguments[2]);
this.arguments = arguments;
}

public static void main(String[] arguments) throws Exception {
Cli cli = new Cli(arguments);
cli.run();
}

public void run() throws Exception {
if (arguments.length > 3) {
executeSql(arguments[3]);
} else {
boolean interactive = true;
if (interactive) {
LineNumberReader reader = new LineNumberReader(new InputStreamReader(System.in));
boolean exit = false;
do {
System.out.print(">> ");
String sql = reader.readLine();
if ("/exit".equalsIgnoreCase(sql.trim())) {
exit = true;
continue;
}
executeSql(sql);
} while (!exit);
}
}
}

private void executeSql(String sql) {
try {
Statement statement = connection.createStatement();
boolean hasResultSet = statement.execute(sql);
if (hasResultSet) {
ResultSet resultSet = statement.getResultSet();
if (resultSet != null) {
int columnCount = resultSet.getMetaData().getColumnCount();
for (int i = 1; i <= columnCount; i++) {
System.out.print(resultSet.getMetaData().getColumnName(i) + "\t");
}
System.out.println();

boolean hasResults = false;
while(resultSet.next()) {
hasResults = true;
for (int i = 1; i <= columnCount; i++) {
System.out.print(resultSet.getString(i) + "\t");
}
System.out.println();
}
if (!hasResults) {
System.out.println("no results");
}
} else {
System.out.println("no results");
}
} else {
int updateCount = statement.getUpdateCount();
if (updateCount == -1) {
System.out.println("Statement executed successfully.");
} else {
System.out.println("Statement executed successfully, " + updateCount + " rows affected.");
}
}
} catch (SQLException e) {
System.out.println("Error executing statement: " + e.getMessage());
}
}
}
4 changes: 2 additions & 2 deletions sql/create/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,14 +26,14 @@ To create the Azure SQL Database setup the environment variables:

<!-- workflow.skip() -->
```shell
export MSSQL_NAME=mssql-$RANDOM
export MSSQL_NAME=joazmssql$RANDOM
export MSSQL_USERNAME=mssql
export MSSQL_PASSWORD=p#ssw0rd-$RANDOM
```

<!-- workflow.run()
if [[ -z $MSSQL_NAME ]]; then
export MSSQL_NAME=mssql-$RANDOM
export MSSQL_NAME=joazmssql$RANDOM
export MSSQL_USERNAME=mssql
export MSSQL_PASSWORD=p#ssw0rd-$RANDOM
fi
Expand Down

This file was deleted.

2 changes: 1 addition & 1 deletion sql/load-your-mssql-database-with-data/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ connect to the database:
```shell
export MSSQL_DNS_NAME=`az sql server show \
--resource-group $RESOURCE_GROUP \
--name $MYSQL_NAME \
--name $MSSQL_NAME \
--query fullyQualifiedDomainName \
--output tsv`

Expand Down
2 changes: 1 addition & 1 deletion sql/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@
<packaging>pom</packaging>
<name>Azure SQL Database</name>
<modules>
<module>cli</module>
<module>create</module>
<module>get-country</module>
<module>load-your-mssql-database-with-data</module>
<module>open-firewall-to-your-ip</module>
</modules>
Expand Down

0 comments on commit 4b002df

Please sign in to comment.