get Short from Database - Java JDBC

Java examples for JDBC:ResultSet

Description

get Short from Database

Demo Code


import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;

public class Main{
    public static short getShort(String row, String table, int id,
            Connection... con) {/*  ww  w. j  ava2 s.  c  o m*/
        String query = "SELECT " + row + " FROM " + table + " WHERE id = ?";

        try {
            Connection connection = con.length > 0 ? con[0] : MySqlManager
                    .getConnection();

            try (PreparedStatement stmt = connection
                    .prepareStatement(query)) {
                stmt.setInt(1, id);
                try (ResultSet rs = stmt.executeQuery()) {
                    if (rs.next()) {
                        return rs.getShort(row);
                    } else {
                        return -1;
                    }
                }
            } finally {
                if (con.length <= 0) {
                    connection.close();
                }
            }
        } catch (SQLException e) {
            return -1;
        }
    }
    public static void setInt(String row, int value, String table, int id,
            Connection... con) {
        String query = "UPDATE " + table + " SET " + row
                + " = ? WHERE id = ?";

        try {
            Connection connection = con.length > 0 ? con[0] : MySqlManager
                    .getConnection();

            try (PreparedStatement stmt = connection
                    .prepareStatement(query)) {
                stmt.setInt(1, value);
                stmt.setInt(2, id);

                stmt.executeUpdate();
            } finally {
                if (con.length <= 0) {
                    connection.close();
                }
            }
        } catch (SQLException ignored) {
        }
    }
}

Related Tutorials