Advertisement
Guest User

Untitled

a guest
Feb 19th, 2019
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 17.15 KB | None | 0 0
  1. package net.dev.art.core.managers;
  2.  
  3. import java.sql.Connection;
  4. import java.sql.Date;
  5. import java.sql.DriverManager;
  6. import java.sql.PreparedStatement;
  7. import java.sql.ResultSet;
  8. import java.sql.ResultSetMetaData;
  9. import java.sql.SQLException;
  10. import java.sql.Statement;
  11. import java.sql.Timestamp;
  12. import java.util.ArrayList;
  13. import java.util.Calendar;
  14. import java.util.HashMap;
  15. import java.util.List;
  16. import java.util.Map;
  17. import java.util.UUID;
  18.  
  19. import org.bukkit.Bukkit;
  20.  
  21. public class DBManager {
  22.  
  23. private String user = "";
  24. private String password = "";
  25. private String host = "";
  26. private String port = "3306";
  27. private String database = "";
  28. private String type = "jdbc:mysql://";
  29. private boolean useSQLite;
  30. private boolean debug = true;
  31. private transient Connection connection;
  32.  
  33. static {
  34. isMySQL();
  35. isSQLite();
  36. }
  37.  
  38. public void sendDebug(String debug) {
  39. if (this.debug) {
  40. Bukkit.getConsoleSender().sendMessage("§8[§aDataBase§8] » §a" + debug);
  41. }
  42. }
  43.  
  44. public void execute(String comando) throws SQLException {
  45. Connection c = getConnection();
  46. PreparedStatement pst;
  47. pst = c.prepareStatement(comando);
  48. pst.executeUpdate();
  49. pst.close();
  50. }
  51.  
  52. public static boolean isMySQL() {
  53. try {
  54. Class.forName("com.mysql.jdbc.Driver");
  55. return true;
  56. } catch (Exception e) {
  57. return false;
  58. }
  59. }
  60.  
  61. public static boolean isSQLite() {
  62. try {
  63. Class.forName("org.sqlite.JDBC");
  64. return true;
  65. } catch (Exception e) {
  66. return false;
  67. }
  68. }
  69.  
  70. public void closeConnection() {
  71. if (hasConnection()) {
  72. try {
  73. this.connection.close();
  74. } catch (SQLException e) {
  75. // TODO Auto-generated catch block
  76. e.printStackTrace();
  77. }
  78. }
  79. }
  80.  
  81. /**
  82. * Cria uma connec§§o com a Database
  83. *
  84. * @return
  85. * @throws Exception
  86. */
  87. public Connection connectBase() throws Exception {
  88. return DriverManager.getConnection(getURL() + database, user, password);
  89. }
  90.  
  91. /**
  92. * Cria uma conne§§o com o Driver
  93. *
  94. * @return
  95. * @throws Exception
  96. */
  97. public Connection connect() throws Exception {
  98. if (useSQLite) {
  99. return DriverManager.getConnection("jdbc:sqlite:" + database);
  100. } else {
  101. return DriverManager.getConnection(getURL(), user, password);
  102. }
  103. }
  104.  
  105. /**
  106. * Cria um Texto baseado nas variaveis
  107. *
  108. * @return Texto estilo URL
  109. */
  110. private String getURL() {
  111. return type + host + ":" + port + "/";
  112. }
  113.  
  114. /**
  115. * Abre a cone§§o com o banco de dados caso n§o exista ainda
  116. *
  117. * @return Mesma instacia da classe DBManager
  118. */
  119. public DBManager openConnection() {
  120. if (!hasConnection()) {
  121. try {
  122. this.connection = connect();
  123. if (!useSQLite) {
  124. createDatabase(database);
  125. useDatabase(database);
  126. }
  127. } catch (Exception e) {
  128. if (isDebugging()) {
  129. e.printStackTrace();
  130. }
  131. }
  132. }
  133.  
  134. return this;
  135. }
  136.  
  137. /**
  138. * Ve se a conec§§o n§o esta nula
  139. *
  140. * @return Se a cone§§o existe
  141. */
  142. public boolean hasConnection() {
  143. return connection != null;
  144. }
  145.  
  146. /**
  147. * Volta a conec§§o da variavel
  148. *
  149. * @return Conec§§o atual
  150. */
  151. public Connection getConnection() {
  152. return connection;
  153. }
  154.  
  155. /**
  156. * Construtor pedindo Usuario, Senha, Host sem conectar com nenhum database
  157. * apenas no Driver
  158. *
  159. * @param user Usuario
  160. * @param pass Senha
  161. * @param host Host
  162. */
  163. public DBManager(String user, String pass, String host) {
  164. this(user, pass, host, "database");
  165. }
  166.  
  167. /**
  168. * Contrutor pedindo Usuario, Senha, Host, Database
  169. *
  170. * @param user Usuario
  171. * @param pass Senha
  172. * @param host Host
  173. * @param database Database
  174. */
  175. public DBManager(String user, String pass, String host, String database) {
  176. this.user = user;
  177. this.password = pass;
  178. this.host = host;
  179. this.database = database;
  180. }
  181.  
  182. /**
  183. * Criar uma database
  184. *
  185. * @param database Database
  186. */
  187. public void createDatabase(String database) {
  188. update("create database if not exists " + database
  189. + " default character set utf8 default collate utf8_general_ci");
  190. }
  191.  
  192. /**
  193. * Conecta com a database
  194. *
  195. * @param database Database
  196. */
  197. public void useDatabase(String database) {
  198. update("USE " + database);
  199. }
  200.  
  201. /**
  202. * Cria uma tabela
  203. *
  204. * @param table Tabela
  205. * @param values Valores
  206. */
  207. public void createTable(String table, String values) {
  208. if (useSQLite) {
  209. update("CREATE TABLE IF NOT EXISTS " + table + " (ID INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT , " + values
  210. + ");");
  211. } else {
  212. update("CREATE TABLE IF NOT EXISTS " + table + " (ID INT NOT NULL AUTO_INCREMENT, " + values
  213. + ", PRIMARY KEY(ID)) default charset = utf8");
  214. }
  215. sendDebug("§eCriado tabela `§b" + table + "§e`.");
  216. }
  217.  
  218. /**
  219. * Deleta todas tabelas da database
  220. *
  221. * @param database Database
  222. */
  223. public void clearDatabase(String database) {
  224. // update("TRUNCATE DATABASE " + database);
  225. }
  226.  
  227. /**
  228. * Deleta database
  229. *
  230. * @param database Database
  231. */
  232. public void deleteDatabase(String database) {
  233. update("DROP DATABASE " + database);
  234. }
  235.  
  236. /**
  237. * Insere um registro
  238. *
  239. * @param table Tabela
  240. * @param objects Objetos
  241. * @return
  242. */
  243. public int insert(String table, Object... objects) {
  244. // if (useSQLite) {
  245. // antes era hashes
  246. return update("INSERT INTO " + table + " values ( NULL , " + getQuestionMarks(objects.length) + " )", objects);
  247. // } else {
  248. // return update("INSERT INTO " + table + " values (default, " + inters(objects.length) + " )", objects);
  249. // }
  250. }
  251.  
  252. /**
  253. * Deleta um registro
  254. *
  255. * @param table Tabela
  256. * @param index Index (ID)
  257. */
  258. public void delete(String table, int index) {
  259. update("DELETE FROM " + table + " WHERE ID = ?", index);
  260. }
  261.  
  262. /**
  263. * Deleta um registro
  264. *
  265. * @param table Tablea
  266. * @param where Como
  267. * @param values Valores
  268. */
  269. public void delete(String table, String where, Object... values) {
  270. update("DELETE FROM " + table + " WHERE " + where, values);
  271. }
  272.  
  273. /**
  274. * Deleta uma coluna
  275. *
  276. * @param table Tale
  277. * @param column Coluna
  278. */
  279. public void delete(String table, String column) {
  280. alter(table, "drop column " + column);
  281. }
  282.  
  283. /**
  284. * Adiciona no Come§o da tabela uma coluna
  285. *
  286. * @param table Tabela
  287. * @param columnComplete Coluna
  288. */
  289. public void addFirst(String table, String columnComplete) {
  290. alter(table, "add column " + columnComplete + " first");
  291. }
  292.  
  293. public void addReference(String table, String key, String references) {
  294. update("ALTER TABLE " + table + " ADD FOREIGN KEY (" + key + ") REFERENCES " + references);
  295. }
  296.  
  297. public void createView(String view, String select) {
  298. update("CREATE OR REPLACE VIEW " + view + " AS " + select);
  299. }
  300.  
  301. public void deleteView(String view) {
  302. update("DROP VIEW " + view);
  303. }
  304.  
  305. /**
  306. * Renomeia a Tabela para uma Nova Tabela
  307. *
  308. * @param table Tabela
  309. * @param newTable Nova tabela
  310. */
  311. public void renameTable(String table, String newTable) {
  312. alter(table, "rename to " + newTable);
  313. }
  314.  
  315. /**
  316. * Modifica uma Coluna de uma Tabela
  317. *
  318. * @param table Tabela
  319. * @param column Coluna
  320. * @param modification Modifica§§o
  321. */
  322. public void modify(String table, String column, String modification) {
  323. alter(table, "modify column " + column + " " + modification);
  324. }
  325.  
  326. /**
  327. * Adiciona chave primaria na tabela
  328. *
  329. * @param table Tabela
  330. * @param key Chave
  331. */
  332. public void addKey(String table, String key) {
  333. alter(table, "add primary key (" + key + ")");
  334. }
  335.  
  336. /**
  337. * Altera uma tabala
  338. *
  339. * @param table
  340. * @param alter
  341. */
  342. public void alter(String table, String alter) {
  343. if (hasConnection())
  344. update("alter table " + table + " " + alter);
  345. }
  346.  
  347. /**
  348. * Modifica alguns registros da tabela
  349. *
  350. * @param table Tabela
  351. * @param where Como
  352. * @param edit Modifica§§o
  353. * @param values Valores
  354. */
  355. public void change(String table, String edit, String where, Object... values) {
  356. update("UPDATE " + table + " SET " + edit + " WHERE " + where, values);
  357. }
  358.  
  359. /**
  360. * Cria um join entre as tabelas
  361. *
  362. * @param table Tabela
  363. * @param joinTable Tabela2
  364. * @param onClause Comparador
  365. * @param select Select completo
  366. * @return ResultSet
  367. */
  368. public ResultSet join(String table, String joinTable, String onClause, String select) {
  369. return select(select + " FROM " + table + " JOIN " + joinTable + " ON " + onClause);
  370. }
  371.  
  372. /**
  373. * Deleta a tabela
  374. *
  375. * @param table Tabela
  376. */
  377. public void deleteTable(String table) {
  378. update("DROP TABLE " + table);
  379. }
  380.  
  381. /**
  382. * Limpa a tabela removendo todos registros
  383. *
  384. * @param table
  385. */
  386. public void clearTable(String table) {
  387. update("TRUNCATE TABLE " + table);
  388. }
  389.  
  390. /**
  391. *
  392. * @param table
  393. * @param where
  394. * @param values
  395. * @return
  396. */
  397. public boolean contains(String table, String where, Object... values) {
  398. return contains("select * from " + table + " where " + where, values);
  399. }
  400.  
  401. /**
  402. * Executa um Select e volta se tem algum registro
  403. *
  404. * @param query Query
  405. * @param replacers Objetos
  406. * @return Se tem ou n§o registro com esta Query
  407. */
  408. public boolean contains(String query, Object... replacers) {
  409. boolean has = false;
  410. if (hasConnection())
  411. try {
  412. ResultSet rs = select(query, replacers);
  413. has = rs.next();
  414. rs.close();
  415.  
  416. } catch (Exception e) {
  417. e.printStackTrace();
  418. }
  419. return has;
  420.  
  421. }
  422.  
  423. /**
  424. * Executa uma Atualiza§§o com um Query
  425. *
  426. * @param query Query Pesquisa
  427. * @param replacers Objetos
  428. * @return
  429. */
  430. public int update(String query, Object... replacers) {
  431. int resultado = -1;
  432. if (hasConnection()) {
  433. try {
  434. PreparedStatement state = query(query, replacers);
  435.  
  436. resultado = state.executeUpdate();
  437. ResultSet keys = state.getGeneratedKeys();
  438. if (keys != null) {
  439. if (keys.next()) {
  440. resultado = keys.getInt(1);
  441. }
  442. }
  443. } catch (Exception e) {
  444. e.printStackTrace();
  445.  
  446. }
  447. }
  448. return resultado;
  449. }
  450.  
  451. /**
  452. * Cria um PreparedStatement com uma Query dada, e aplica os Replacers
  453. *
  454. * @param query Query
  455. * @param replacers Objetos
  456. * @return PreparedStatement (Estado da Query)
  457. */
  458.  
  459. public static String getQuestionMarks(int size) {
  460. StringBuilder builder = new StringBuilder();
  461. for (int i = 0; i < size; i++) {
  462. if (i != 0)
  463. builder.append(",");
  464. builder.append("?");
  465. }
  466. return builder.toString();
  467. }
  468.  
  469. public static void setSQLValue(PreparedStatement state, int param, Object value) {
  470. try {
  471. state.setString(param, fromJavaToSQL(value));
  472. } catch (SQLException e) {
  473. // TODO Auto-generated catch block
  474. e.printStackTrace();
  475. }
  476. }
  477.  
  478. public static String fromJavaToSQL(Object value) {
  479. if (value == null) {
  480. return "NULL";
  481. }
  482. Class<? extends Object> type = value.getClass();
  483. if (type == java.util.Date.class) {
  484. value = new Date(((java.util.Date) value).getTime());
  485. } else if (value instanceof Calendar) {
  486. value = new Timestamp(((Calendar) value).getTimeInMillis());
  487. }
  488.  
  489. return value.toString();
  490. }
  491.  
  492. public PreparedStatement query(String query, Object... replacers) {
  493. try {
  494. if (!query.endsWith(";")) {
  495. query += ";";
  496. }
  497.  
  498. PreparedStatement state = connection.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
  499.  
  500. int id = 1;
  501. for (Object replacer : replacers) {
  502. setSQLValue(state, id, replacer);
  503. query.replaceFirst("\\?", "'" + fromJavaToSQL(replacer) + "'");
  504. id++;
  505. }
  506.  
  507. return state;
  508. } catch (Exception e) {
  509. e.printStackTrace();
  510. }
  511. return null;
  512. }
  513.  
  514. public String getString(String table, String column, String where, Object... replacers) {
  515. String result = "";
  516. ResultSet rs = selectAll(table, where, replacers);
  517. try {
  518. if (rs.next()) {
  519. result = rs.getString(column);
  520. }
  521. rs.close();
  522. } catch (Exception e) {
  523. e.printStackTrace();
  524. }
  525. ;
  526. return result;
  527. }
  528.  
  529. public Date getDate(String table, String column, String where, Object... replacers) {
  530. Date result = null;
  531. ResultSet rs = selectAll(table, where, replacers);
  532. try {
  533. if (rs.next()) {
  534. result = rs.getDate(column);
  535. }
  536. rs.close();
  537. } catch (Exception e) {
  538. e.printStackTrace();
  539. }
  540.  
  541. return result;
  542. }
  543.  
  544. public UUID getUUID(String table, String column, String where, Object... replacers) {
  545. return UUID.fromString(getString(table, column, where, replacers));
  546. }
  547.  
  548. public int getInt(String table, String column, String where, Object... replacers) {
  549. int result = -1;
  550. ResultSet rs = selectAll(table, where, replacers);
  551. try {
  552. if (rs.next()) {
  553. result = rs.getInt(column);
  554. }
  555. rs.close();
  556. } catch (Exception e) {
  557. e.printStackTrace();
  558. }
  559.  
  560. return result;
  561. }
  562.  
  563. public double getDouble(String table, String column, String where, Object... replacers) {
  564. double result = -1;
  565. ResultSet rs = selectAll(table, where, replacers);
  566. try {
  567. if (rs.next()) {
  568. result = rs.getDouble(column);
  569. }
  570. rs.close();
  571. } catch (Exception e) {
  572. e.printStackTrace();
  573. }
  574. return result;
  575. }
  576.  
  577. public ResultSet selectAll(String table, String where, Object... replacers) {
  578. return select("SELECT * FROM " + table + " WHERE " + where, replacers);
  579. }
  580.  
  581. /**
  582. * Executa um Query e volta um ResultSet
  583. *
  584. * @param query Pesquisa
  585. * @param replacers Objetos
  586. * @return ResultSet (Resultado da Query)
  587. */
  588. public ResultSet select(String query, Object... replacers) {
  589. try {
  590. return query(query, replacers).executeQuery();
  591. } catch (Exception e) {
  592. e.printStackTrace();
  593. return null;
  594. }
  595.  
  596. }
  597.  
  598. public String getUser() {
  599. return user;
  600. }
  601.  
  602. public void setUser(String user) {
  603. this.user = user;
  604. }
  605.  
  606. public String getPassword() {
  607. return password;
  608. }
  609.  
  610. public void setPassword(String password) {
  611. this.password = password;
  612. }
  613.  
  614. public String getHost() {
  615. return host;
  616. }
  617.  
  618. public void setHost(String host) {
  619. this.host = host;
  620. }
  621.  
  622. public String getPort() {
  623. return port;
  624. }
  625.  
  626. public void setPort(String port) {
  627. this.port = port;
  628. }
  629.  
  630. public String getDatabase() {
  631. return database;
  632. }
  633.  
  634. public void setDatabase(String database) {
  635. this.database = database;
  636. }
  637.  
  638. public String getType() {
  639. return type;
  640. }
  641.  
  642. public void setType(String type) {
  643. this.type = type;
  644. }
  645.  
  646. // private String hashes(int size) {
  647. // StringBuilder builder = new StringBuilder();
  648. // for (int i = 0; i < size; i++) {
  649. // if (i != 0)
  650. // builder.append(",");
  651. // builder.append("#");
  652. // }
  653. // return builder.toString();
  654. // }
  655.  
  656. @Override
  657. public String toString() {
  658. return "DBManager [user=" + user + ", pass=" + password + ", host=" + host + ", port=" + port + ", database="
  659. + database + ", type=" + type + "]";
  660. }
  661.  
  662. public boolean useSQLite() {
  663. return useSQLite;
  664. }
  665.  
  666. public void setUseSQLite(boolean useSQLite) {
  667. this.useSQLite = useSQLite;
  668. }
  669.  
  670. /**
  671. * Seleciona tudo que o Select volta e transforma em Lista de Mapa<br>
  672. * Lista = Linhas<br>
  673. * Mapa = Colunas<br>
  674. *
  675. * @param query Query
  676. * @param replacers Objetos
  677. * @return Lista de Mapa
  678. */
  679. public List<Map<String, Object>> getResult(String query, Object... replacers) {
  680. List<Map<String, Object>> list = new ArrayList<>();
  681. try {
  682. ResultSet rs = select(query, replacers);
  683.  
  684. while (rs.next()) {
  685. Map<String, Object> mapa = new HashMap<>();
  686. ResultSetMetaData meta = rs.getMetaData();
  687. for (int i = 1; i <= meta.getColumnCount(); i++) {
  688. String name = meta.getColumnName(i);
  689. mapa.put(name, rs.getObject(name));
  690. }
  691. list.add(mapa);
  692. }
  693. rs.close();
  694.  
  695. } catch (Exception e) {
  696. e.printStackTrace();
  697. }
  698. return list;
  699. }
  700.  
  701. public List<Map<String, Object>> getAllResult(String table, Object... replacers) {
  702. return getResult("select * from " + table, replacers);
  703. // List<Map<String, Object>> lista = new ArrayList<>();
  704. // try {
  705. // ResultSet rs = select("SELECT * FROM " + table, replacers);
  706. // while (rs.next()) {
  707. // Map<String, Object> mapa = new HashMap<>();
  708. // ResultSetMetaData meta = rs.getMetaData();
  709. // for (int colunaId = 1; colunaId <= meta.getColumnCount(); colunaId++) {
  710. // String name = meta.getColumnName(colunaId);
  711. // mapa.put(name, rs.getObject(name));
  712. // }
  713. // lista.add(mapa);
  714. // }
  715. // rs.close();
  716. //
  717. // } catch (Exception e) {
  718. // e.printStackTrace();
  719. // }
  720. // return lista;
  721. }
  722.  
  723. public Map<String, Object> getOneResult(String table, Object... replacers) {
  724. List<Map<String, Object>> all = getAllResult(table, replacers);
  725. if (!all.isEmpty()) {
  726. return all.get(0);
  727. }
  728. HashMap<String, Object> mapa = new HashMap<>();
  729. try {
  730. ResultSet rs = select("SELECT * FROM " + table, replacers);
  731. if (rs.next()) {
  732. ResultSetMetaData meta = rs.getMetaData();
  733. for (int colunaId = 1; colunaId <= meta.getColumnCount(); colunaId++) {
  734. String name = meta.getColumnName(colunaId);
  735. mapa.put(name, rs.getObject(name));
  736. }
  737. }
  738. rs.getStatement().getConnection().close();
  739.  
  740. } catch (Exception e) {
  741. e.printStackTrace();
  742. }
  743. return mapa;
  744. }
  745.  
  746. public boolean isDebugging() {
  747. return debug;
  748. }
  749.  
  750. public void setDebug(boolean d) {
  751. debug = d;
  752. }
  753.  
  754. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement