Advertisement
osx11

[Java] MySQL

Nov 27th, 2018
194
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.91 KB | None | 0 0
  1. import java.sql.Connection;
  2. import java.sql.DriverManager;
  3. import java.sql.SQLException;
  4. import java.sql.Statement;
  5.  
  6. public class MySQL {
  7.  
  8.     private Connection connection;
  9.  
  10.     private String login = "login";
  11.     private String password = "password"
  12.     private String url = "jdbc:mysql://address:port/database";
  13.  
  14.     public Connection getConnection() throws SQLException {
  15.         if (login != null)
  16.             return DriverManager.getConnection(url, login, password);
  17.         else return DriverManager.getConnection(url);
  18.     }
  19.  
  20.     public void query(final String sql) { // выполнить запрос
  21.         try {
  22.  
  23.             try {
  24.                 connection = getConnection();
  25.             } catch (Exception e) {
  26.                 System.out.println("MySQL connection error");
  27.                 e.printStackTrace();
  28.             }
  29.  
  30.             Statement statement = connection.createStatement();
  31.             statement.executeUpdate(sql);
  32.             statement.close();
  33.             connection.close();
  34.  
  35.         } catch (Exception e) {
  36.             e.printStackTrace();
  37.         }
  38.     }
  39.  
  40.     public static String getString(final String query, final String columnLabel) { // вытащить данные
  41.         String result = null;
  42.         try {
  43.             try {
  44.                 connection = getConnection();
  45.             } catch (Exception e) {
  46.                 System.out.println("MySQL connection error");
  47.                 e.printStackTrace();
  48.             }
  49.  
  50.             final Statement statement = connection.createStatement();
  51.  
  52.             final ResultSet resultSet = statement.executeQuery(query);
  53.             if (resultSet.next()) {
  54.                 result = resultSet.getString(columnLabel);
  55.             }
  56.  
  57.             statement.close();
  58.             connection.close();
  59.  
  60.         } catch (Exception e) {
  61.             e.printStackTrace();
  62.         }
  63.  
  64.         return result;
  65.     }
  66.  
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement