Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static String url;
- public static String driver;
- public static Connection con = null;
- public MySQL(final String host, final String db, final String username, final String password) {
- //Tworzymy nową instancje bazy danych i nawiązujemy połączenie. w hoscie musi znajdować się też port servera MySQL
- MySQL.url = "jdbc:mysql://" + host + "/" + db + "?user=" + username + "&password=" + password;
- MySQL.driver = ("com.mysql.jdbc.Driver");
- }
- // Metoda od otwierania połączenia, zwykle używasz tylko raz :P
- public Connection open() throws SQLException, ClassNotFoundException {
- Class.forName(MySQL.driver);
- MySQL.con = DriverManager.getConnection(MySQL.url);
- return MySQL.con;
- }
- // Tej metody używasz w onEnable by połączyć się z bazą danych. Oczywiście nie musi byc boolean
- // ale dzięki temu mogę odrazu sprawdzic czy sie w miare udało :P
- public static boolean connectToDatabase() {
- try {
- MySQL.con = new MySQL("localhost", "baza", "root", "dobrehaslo33").open();
- return true;
- } catch (ClassNotFoundException | SQLException e) {
- e.printStackTrace();
- return false;
- }
- }
- // Tutaj sobie tworze tabelki :>
- public static void createTables(String ...sb) throws SQLException {
- DbStatement stat = createStatement(sb);
- // Bardzo ważne by zawsze na końiec zamykać statement
- stat.runAndClose();
- }
- private static void isConnected() throws SQLException{
- if(con.isClosed() || con == null){
- connectToDatabase();
- }
- }
- // Tutaj są 4 wygodne metody od używania bazy danych :>
- //Tworzy nowy statement, od używania UUPDATE, INSERT itp w argumentach podajesz wszystkie potrzebne SQL-e
- public static DbStatement createStatement(final String... sqls) throws SQLException {
- isConnected();
- return new DbStatement(con.createStatement(), sqls);
- }
- // To odrazu tworzy i uruchamia i zamyka statement :> czyli jak chcesz tylko szybko wykonać jakąs komende i tyle.
- public static void runStatement(final String... sqls) throws SQLException {
- isConnected();
- new DbStatement(con.createStatement(), sqls).runAndClose();
- }
- //To samo co 1, ale jest czysty na początku (mozna potem dodac itp :>)
- public static DbStatement createStatement() throws SQLException {
- isConnected();
- return new DbStatement(con.createStatement());
- }
- // A to od używania SELECT :P po skończeniu zabawy z select też należy zamknąc :>
- public static DbResult getResult(String sql) throws SQLException {
- isConnected();
- return new DbResult(con.createStatement(), sql);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement