Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package pks.database;
- import java.sql.CallableStatement;
- import java.sql.Connection;
- import java.sql.Date;
- import java.sql.DriverManager;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.sql.Time;
- import java.sql.Timestamp;
- public class DatabaseConnector
- {
- private static Connection connection = null;
- public static void connect(String host, String database, String username, String password) throws Exception
- {
- Class.forName("com.mysql.jdbc.Driver");
- connection = DriverManager.getConnection("jdbc:mysql://" + host + "/" + database + "?" + "user=" + username+ "&password" + password + "&characterEncoding=utf-8");
- }
- public static ResultSet getCourseList(String cityA, String cityB, String date) throws SQLException
- {
- CallableStatement call = connection.prepareCall("{ call KursyMiedzyPrzystankami(?, ?, ?)}");
- call.setString(1, cityA);
- call.setString(2, cityB);
- call.setDate(3, java.sql.Date.valueOf(date));
- System.out.println(call);
- ResultSet resultSet = call.executeQuery();
- return resultSet;
- }
- private static void setStatementArguments(PreparedStatement statement, Object... args) throws SQLException
- {
- int i = 1;
- for (Object arg : args)
- {
- Class<?> c = arg.getClass();
- if (c.equals(String.class))
- statement.setString(i, (String)arg);
- else if (c.equals(Integer.class))
- statement.setInt(i, (Integer)arg);
- else if (c.equals(Date.class) || c.equals(java.util.Date.class))
- statement.setDate(i, (Date)arg);
- else if (c.equals(Time.class))
- statement.setTime(i, (Time)arg);
- else if (c.equals(Timestamp.class))
- statement.setTimestamp(i, (Timestamp)arg);
- else if (c.equals(Float.class))
- statement.setFloat(i, (Float)arg);
- i++;
- }
- System.out.println(statement);
- }
- public static ResultSet executeCall(String query, Object ... args) throws SQLException
- {
- CallableStatement call = connection.prepareCall("{ " + query + " }");
- setStatementArguments(call, args);
- return call.executeQuery();
- }
- public static ResultSet executeQuery(String query, Object... args) throws SQLException
- {
- PreparedStatement statement = connection.prepareStatement(query);
- setStatementArguments(statement, args);
- return statement.executeQuery();
- }
- public static void executeUpdate(String query, Object... args) throws SQLException
- {
- PreparedStatement statement = connection.prepareStatement(query);
- setStatementArguments(statement, args);
- statement.executeUpdate();
- }
- }
Add Comment
Please, Sign In to add comment