Skip to content

Instantly share code, notes, and snippets.

@pablohdzvizcarra
Created July 13, 2021 16:56
Show Gist options
  • Save pablohdzvizcarra/e3875c8315a3ef25cb916c3671ac1e23 to your computer and use it in GitHub Desktop.
Save pablohdzvizcarra/e3875c8315a3ef25cb916c3671ac1e23 to your computer and use it in GitHub Desktop.
example two procedures operation with mysql
package com.pluralsight.jdbc.course.m6c2;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class Procedures
{
private static final String URL
= "jdbc:mysql://localhost:3306/classicmodels?user=root&password=my-secret-pw";
public static void main(String[] args) throws SQLException
{
String nameColumn = "Motorcycles";
List<String> list = Procedures.listProductsBy(nameColumn);
list.forEach(System.out::println);
int numEmployee = 1002;
String newEmail = "[email protected]";
String oldEmail = Procedures.updateEmail(numEmployee, newEmail);
if (oldEmail != null)
{
System.out.println("SUCCESS: update");
} else
{
System.out.println("FAIL: occurred");
}
}
public static List<String> listProductsBy(String productLine) throws SQLException
{
List<String> nameList = new ArrayList<>();
try(Connection connection = DriverManager.getConnection(URL);
CallableStatement callableStatement =
connection.prepareCall("{call listProductsFor(?)}"))
{
callableStatement.setString(1, productLine);
boolean success = callableStatement.execute();
if (success)
{
try(ResultSet resultSet = callableStatement.getResultSet())
{
while (resultSet.next())
{
String name = resultSet.getString("productName");
nameList.add(name);
}
return nameList;
}
}
}
return nameList;
}
public static String updateEmail(int employeeNumber, String newEmail) throws SQLException
{
try(Connection connection = DriverManager.getConnection(URL);
CallableStatement callableStatement =
connection.prepareCall("{call updateEmail(?, ?)}"))
{
callableStatement.setInt(1, employeeNumber);
callableStatement.registerOutParameter(2, java.sql.Types.VARCHAR);
callableStatement.setString(2, newEmail);
callableStatement.execute();
String oldEmail = callableStatement.getString(2);
return oldEmail;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment