Advertisement
DeveloperSergio

Java GUI Vs mysql database Part 5

Nov 25th, 2016
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 25.51 KB | None | 0 0
  1. import javax.swing.*;
  2. import java.sql.*;
  3.  
  4. /**
  5. * Created by Admin on 24.11.2016.
  6. */
  7. public class AddValsInMysql {
  8.  
  9. //создаем значения в БД
  10. void createValsInMysql(JTextField field1, JTextField field2, JTextField field3, JTextField field4, JTextField field5,
  11. Connection con, Statement stmt, ResultSet rs, String url, String user, String password){
  12.  
  13.  
  14. String query = "INSERT INTO carsfff.tbl1 (CODE, TYPE, QUANTITY, PRICE, YEAR) VALUES (" +
  15. "'" + field1.getText() + "'" + "," +
  16. "'" + field2.getText() + "'" + "," +
  17. "'" + field3.getText() + "'" + "," +
  18. "'" + field4.getText() + "'" + "," +
  19. "'" + field5.getText() + "'" + ")";
  20. try {
  21. // opening database connection to MySQL server
  22. con = DriverManager.getConnection(url, user, password);
  23.  
  24. // getting Statement object to execute query
  25. stmt = con.createStatement();
  26.  
  27.  
  28. /*Ввод строк JTextfields в таблицу mysql*/
  29. stmt.executeUpdate(query);
  30.  
  31. } catch (SQLException sqlEx) {
  32. sqlEx.printStackTrace();
  33. } finally {
  34. //close connection ,stmt and resultset here
  35. try { con.close(); } catch(SQLException se) { /*can't do anything */ }
  36. try { stmt.close(); } catch(SQLException se) { /*can't do anything */ }
  37. try { rs.close(); } catch(SQLException se) { /*can't do anything */ }
  38. }
  39.  
  40. }
  41.  
  42. }
  43.  
  44.  
  45. import javax.swing.*;
  46. import java.awt.event.ActionEvent;
  47. import java.awt.event.ActionListener;
  48. import java.sql.Connection;
  49. import java.sql.ResultSet;
  50. import java.sql.Statement;
  51. import java.util.ArrayList;
  52.  
  53. /**
  54. * Created by Admin on 24.11.2016.
  55. */
  56. public class ButtonUpdateActListn {
  57.  
  58. Message messageUpdate = new Message();
  59.  
  60. void btnUpActListen(JButton btnUpdate, ArrayList valueInTables, JTextField field1, JTextField field2,
  61. JTextField field3, JTextField field4, JTextField field5, JTextField fieldID ,
  62. UpdateStringInTable updateStringInTable, String url, String user, String password,
  63. Connection con, Statement stmt, ResultSet rs, MyTableModel tModel){
  64.  
  65. // данные изменяются в таблице. Слушатель на кнопку
  66. btnUpdate.addActionListener(new ActionListener() {
  67. @Override
  68. public void actionPerformed(ActionEvent ae) {
  69.  
  70. valueInTables.add(new ValueInTable(field1.getText(), field2.getText(),
  71. Integer.valueOf(field3.getText()), Integer.valueOf(field4.getText()),
  72. Integer.valueOf(field5.getText()) ) );
  73.  
  74. updateStringInTable.updateValues(url, user, password, field1, field2, field3, field4, field5,
  75. con, stmt, rs, Integer.valueOf(fieldID.getText()) );
  76.  
  77. // выводим сообщение посне нажатия кнопки
  78. messageUpdate.showMsDialogBtnUpdate(ae, btnUpdate, Integer.valueOf(String.valueOf(fieldID.getText())));
  79.  
  80. tModel.fireTableDataChanged();
  81. }
  82. });
  83. }
  84. }
  85.  
  86.  
  87. import java.sql.*;
  88.  
  89. /**
  90. * Created by Admin on 24.11.2016.
  91. */
  92. public class GetCountToAllRowsInMysql {
  93.  
  94. //узнаем к-тво строк в БД
  95. public int getAllRowsMysql(Connection con, Statement stmt, ResultSet rs, String url, String user, String password){
  96.  
  97. String query = "SELECT count(*) FROM tbl1";
  98. int allRows = 0;
  99. try {
  100. // opening database connection to MySQL server
  101. con = DriverManager.getConnection(url, user, password);
  102.  
  103. // getting Statement object to execute query
  104. stmt = con.createStatement();
  105.  
  106. // executing SELECT query
  107. rs = stmt.executeQuery(query);
  108.  
  109.  
  110. /*Вывод строки таблици*/
  111. while (rs.next()) {
  112. allRows = rs.getInt(1);
  113. }
  114.  
  115.  
  116. } catch (SQLException sqlEx) {
  117. sqlEx.printStackTrace();
  118. } finally {
  119. //close connection ,stmt and resultset here
  120. try { con.close(); } catch(SQLException se) { /*can't do anything */ }
  121. try { stmt.close(); } catch(SQLException se) { /*can't do anything */ }
  122. try { rs.close(); } catch(SQLException se) { /*can't do anything */ }
  123. }
  124.  
  125. return allRows;
  126. }
  127.  
  128.  
  129. }
  130.  
  131.  
  132. import javax.swing.*;
  133. import javax.swing.event.TableModelEvent;
  134. import javax.swing.table.DefaultTableModel;
  135. import java.awt.*;
  136. import java.awt.event.ActionEvent;
  137. import java.awt.event.ActionListener;
  138. import java.sql.*;
  139. import java.util.ArrayList;
  140. import java.util.Vector;
  141.  
  142. /**
  143. * Created by Admin on 18.11.2016.
  144. */
  145. public class JTableWindow extends JFrame{
  146.  
  147. private static final String url = "jdbc:mysql://localhost:3306/carsfff";
  148. private static final String user = "root";
  149. private static final String password = "root";
  150.  
  151.  
  152. // поля для открытия подключения и получения значенией с Mysql
  153. private static Connection con;
  154. private static Statement stmt;
  155. private static ResultSet rs;
  156.  
  157. Vector<Object> vector = new Vector<>();
  158. //Создадим список из сущностей класса ValueInTable
  159. ArrayList valueInTables = new ArrayList();
  160.  
  161.  
  162. UpdateStringInTable updateStringInTable = new UpdateStringInTable();
  163. SizeButtons sizeButtons = new SizeButtons();
  164. //JButton Update слушатель
  165. ButtonUpdateActListn buttonUpdateActListn = new ButtonUpdateActListn();
  166. // класс по созданию значенией в Mysql
  167. AddValsInMysql addValsInMysql = new AddValsInMysql();
  168. // класс с методом getAllRowsMysql() для получения значения всех строк
  169. GetCountToAllRowsInMysql getCountToAllRowsInMysql = new GetCountToAllRowsInMysql();
  170. // класс с методом removeRowById() // удаляем строку по id
  171. RemoveRowInMysql removeRowInMysql = new RemoveRowInMysql();
  172. // класс с методом showMsDialog() диологовых окон Message
  173. Message message = new Message();
  174. // класс с методом setIdAutoIncrement() перемещает AUTO_INCREMENT на последний элемент ID после удаления
  175. RefreshAutoIncrementForID refreshAutoIncrementForID = new RefreshAutoIncrementForID(con, stmt, rs, url, user, password);
  176.  
  177.  
  178. JButton btnUpdate = new JButton("Update");
  179. JButton btnAdd = new JButton("Add");
  180. JButton btnRemove = new JButton("Remove");
  181. JButton btnRefresh = new JButton("Refresh");
  182. JLabel labelID = new JLabel("ID:");
  183.  
  184.  
  185. // размер поля field 5
  186. JTextField field1 = new JTextField(5);
  187. JTextField field2 = new JTextField(5);
  188. JTextField field3 = new JTextField(5);
  189. JTextField field4 = new JTextField(5);
  190. JTextField field5 = new JTextField(5);
  191. JTextField fieldID = new JTextField(2);
  192.  
  193. //Объект таблицы
  194. JTable jTable;
  195.  
  196.  
  197.  
  198. JTableWindow() {
  199.  
  200. //вводим запрос ID в mysql
  201. addIdInTable();
  202.  
  203.  
  204. //Создаем новый контейнер JFrame
  205. JFrame jFrame = new JFrame("Mysql V2.0");
  206.  
  207. //размер JButton задает метод sizeBtn() в класе SizeButtons
  208. sizeButtons.sizeBtn(btnUpdate, btnAdd, btnRemove, btnRefresh);
  209.  
  210.  
  211. //Устанавливаем диспетчер компоновки
  212. jFrame.getContentPane().setLayout(new FlowLayout());
  213.  
  214.  
  215. //Устанавливаем размер окна
  216. jFrame.setSize(580, 470);
  217.  
  218. //Устанавливаем завершение программы при закрытии окна
  219. jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  220.  
  221. jFrame.add(field1);
  222. jFrame.add(field2);
  223. jFrame.add(field3);
  224. jFrame.add(field4);
  225. jFrame.add(field5);
  226.  
  227. jFrame.add(labelID);
  228.  
  229.  
  230. // получаем данные с конструктора ValueInTables
  231. getArrayListVal(valueInTables);
  232.  
  233.  
  234. //Создадим модель таблицы
  235. MyTableModel tModel = new MyTableModel(valueInTables);
  236.  
  237.  
  238. //вызов метода слушутеля кнопки JButtonUpdate
  239. buttonUpdateActListn.btnUpActListen(btnUpdate, valueInTables, field1,field2,
  240. field3,field4,field5,fieldID, updateStringInTable, url, user, password, con, stmt, rs, tModel);
  241.  
  242.  
  243. // данные обновляются в таблице слушатель на кнопку
  244. btnRefresh.addActionListener(new ActionListener() {
  245. @Override
  246. public void actionPerformed(ActionEvent ae) {
  247.  
  248. // обнуляем ArrayList
  249. valueInTables.clear();
  250. // обуляем вектор
  251. vector.clear();
  252. // заполняем Vector данными с mysql
  253. addIdInTable();
  254. getArrayListVal(valueInTables);
  255. //вызываем метод для вывода сообщения после нажатия кнопки
  256. message.showMsDialogBtnRefresh(ae, btnRefresh);
  257.  
  258. tModel.fireTableDataChanged();
  259. }
  260. });
  261.  
  262. // вызов метода createValsInMysql(), данные добавляются в таблицу Mysql. Слушатель на кнопку
  263. btnAdd.addActionListener(new ActionListener() {
  264. @Override
  265. public void actionPerformed(ActionEvent ae) {
  266. // создание записей в Mysql
  267. addValsInMysql.createValsInMysql(field1, field2, field3, field4, field5,
  268. con, stmt, rs, url, user, password);
  269. // вывод сообщения после нажатия кнопки о добавлении строки с ID
  270. message.showMsDialogBtnAdd(ae, btnAdd);
  271.  
  272. tModel.fireTableDataChanged();
  273. }
  274. });
  275.  
  276.  
  277. // слушатель на кнопку Remove
  278. btnRemove.addActionListener(new ActionListener() {
  279. @Override
  280. public void actionPerformed(ActionEvent ae) {
  281.  
  282. // удаление строк в Mysql по id
  283. removeRowInMysql.removeRowById(con, stmt, rs, url, user, password,
  284. Integer.valueOf(String.valueOf(fieldID.getText())));
  285. // выводим сообщение после удаления
  286. message.showMsDialogBtnRemove(ae, btnRemove, Integer.valueOf(String.valueOf(fieldID.getText())) );
  287.  
  288. // перемещаем auto_increment ID на последний елемент ID
  289. refreshAutoIncrementForID.setIdAutoIncrement();
  290.  
  291. tModel.fireTableDataChanged();
  292. }
  293. });
  294.  
  295.  
  296. //На основе модели, создадим новую JTable
  297. jTable = new JTable(tModel);
  298.  
  299.  
  300.  
  301. //Создаем панель прокрутки и включаем в ее состав нашу таблицу
  302. JScrollPane jscrlp = new JScrollPane(jTable);
  303.  
  304.  
  305. //Устаналиваем размеры прокручиваемой области
  306. jTable.setPreferredScrollableViewportSize(new Dimension(550, 200));
  307.  
  308. //Добавляем в контейнер нашу панель прокрути и таблицу вместе с ней
  309. jFrame.getContentPane().add(jscrlp);
  310.  
  311.  
  312. // добавляем кнопку на JFrame
  313. jFrame.getContentPane().add( labelID );
  314. jFrame.getContentPane().add( fieldID );
  315. jFrame.getContentPane().add( btnUpdate );
  316. jFrame.getContentPane().add( btnRefresh );
  317. jFrame.getContentPane().add( btnAdd );
  318. jFrame.getContentPane().add( btnRemove );
  319.  
  320.  
  321.  
  322. // отображение фрейма по центру
  323. jFrame.setLocationRelativeTo(null);
  324.  
  325. //Отображаем контейнер
  326. jFrame.setVisible(true);
  327. }
  328.  
  329.  
  330.  
  331. //в Vector-лист добавляются значения каждая новая строка по номеру id
  332. public void conToMysql(int id){
  333.  
  334. String query = "SELECT * FROM tbl1 where id=" + "'" + id + "'";
  335.  
  336. try {
  337. // opening database connection to MySQL server
  338. con = DriverManager.getConnection(url, user, password);
  339.  
  340. // getting Statement object to execute query
  341. stmt = con.createStatement();
  342.  
  343. // executing SELECT query
  344. rs = stmt.executeQuery(query);
  345.  
  346. // к-тво всех столбцов в таблице
  347. int allCol = rs.getMetaData().getColumnCount();
  348.  
  349. /*Вывод всей строки таблици из БД в Vector*/
  350. while (rs.next()) {
  351. for (int i = 1; i <= allCol; i++) {
  352. vector.add(rs.getObject(i));
  353. }
  354. }
  355.  
  356.  
  357. } catch (SQLException sqlEx) {
  358. sqlEx.printStackTrace();
  359. } finally {
  360. //close connection ,stmt and resultset here
  361. try { con.close(); } catch(SQLException se) { /*can't do anything */ }
  362. try { stmt.close(); } catch(SQLException se) { /*can't do anything */ }
  363. try { rs.close(); } catch(SQLException se) { /*can't do anything */ }
  364. }
  365.  
  366.  
  367. }
  368.  
  369.  
  370. // метод с соединением и обновлением таблицы
  371. void addIdInTable(){
  372. for (int id = 1; id <= getCountToAllRowsInMysql.getAllRowsMysql(con, stmt, rs, url, user, password); id++)
  373. conToMysql(id);
  374. }
  375.  
  376. // получение ячеек таблицы с конструктора ValueInTable()
  377. void getArrayListVal(ArrayList valueInTables){
  378.  
  379. int getAllRows = getCountToAllRowsInMysql.getAllRowsMysql(con,stmt,rs,url,user,password);
  380. // получаем значения с Vector-а и выводим их в JTAble
  381. for (int val0 = 0, val1 = 1, val2 = 2, val3 = 3, val4 = 4, val5 = 5; val5 < 6 * getAllRows; val0 +=6, val1 +=6, val2 +=6, val3 +=6, val4 +=6, val5 +=6 ) {
  382. valueInTables.add( new ValueInTable(vector.get(val0), vector.get(val1), vector.get(val2),
  383. vector.get(val3), vector.get(val4), vector.get(val5) ));
  384. }
  385.  
  386. }
  387.  
  388.  
  389.  
  390. //Функция main, запускающаяся при старте приложения
  391. public static void main(String[] args) {
  392.  
  393. //Создаем фрейм в потоке обработки событий
  394. SwingUtilities.invokeLater(new Runnable() {
  395. @Override
  396. public void run() {
  397. new JTableWindow();
  398. }
  399. });
  400. }
  401. }
  402.  
  403.  
  404. import javax.swing.*;
  405. import java.awt.*;
  406. import java.awt.event.ActionEvent;
  407.  
  408. /**
  409. * Created by Admin on 25.11.2016.
  410. */
  411. public class Message {
  412.  
  413. public void showMsDialogBtnRefresh(ActionEvent event, JButton btnRefresh) {
  414. if (event.getSource() == btnRefresh) {
  415. JOptionPane.showMessageDialog(btnRefresh, "Таблица обновлена",
  416. "Message Information", JOptionPane.INFORMATION_MESSAGE);
  417. }
  418. }
  419.  
  420. public void showMsDialogBtnUpdate(ActionEvent event, JButton btnUpdate, int id) {
  421. if (event.getSource() == btnUpdate){
  422. JOptionPane.showMessageDialog(btnUpdate, "Поле ID "+ id +" обновлено",
  423. "Message Information" , JOptionPane.INFORMATION_MESSAGE);
  424. }
  425. }
  426.  
  427. public void showMsDialogBtnAdd(ActionEvent event, JButton btnAdd) {
  428. if (event.getSource() == btnAdd){
  429. JOptionPane.showMessageDialog(btnAdd, "Строка добавлена",
  430. "Message Information", JOptionPane.INFORMATION_MESSAGE);
  431. }
  432. }
  433.  
  434. public void showMsDialogBtnRemove(ActionEvent event, JButton btnRemove, int id) {
  435. if (event.getSource() == btnRemove){
  436. JOptionPane.showMessageDialog(btnRemove, "Поле ID "+ id +" удалено",
  437. "Message Information", JOptionPane.INFORMATION_MESSAGE);
  438. }
  439. }
  440. }
  441.  
  442.  
  443. import javax.swing.table.AbstractTableModel;
  444. import java.util.ArrayList;
  445.  
  446. /**
  447. * Created by Admin on 18.11.2016.
  448. */
  449.  
  450.  
  451. public class MyTableModel extends AbstractTableModel{
  452.  
  453. ArrayList<ValueInTable> valueInTable;
  454.  
  455. MyTableModel(ArrayList<ValueInTable> valueInTable){
  456. super();
  457. this.valueInTable = valueInTable;
  458. }
  459.  
  460. @Override
  461. public int getRowCount() {
  462. return valueInTable.size();
  463. }
  464.  
  465.  
  466. // к-тво столбцов
  467. @Override
  468. public int getColumnCount() {
  469. return 6;
  470. }
  471.  
  472. //данные в ячейке
  473. @Override
  474. public Object getValueAt(int rowIndex, int columnIndex) {
  475. if (columnIndex == 0)
  476. return valueInTable.get(rowIndex).getId();
  477. else if (columnIndex == 1)
  478. return valueInTable.get(rowIndex).getCode();
  479. else if (columnIndex == 2)
  480. return valueInTable.get(rowIndex).getType();
  481. else if (columnIndex == 3)
  482. return valueInTable.get(rowIndex).getQuantity();
  483. else if (columnIndex == 4)
  484. return valueInTable.get(rowIndex).getPrice();
  485. else if (columnIndex == 5)
  486. return valueInTable.get(rowIndex).getYear();
  487. else
  488. return "Other_Column";
  489.  
  490. }
  491.  
  492. public String getColumnName(int c){
  493. if (c == 0)
  494. return "id";
  495. else if (c == 1)
  496. return "Code ";
  497. else if (c == 2)
  498. return "Type ";
  499. else if (c == 3)
  500. return "Quantity ";
  501. else if (c == 4)
  502. return "Price ";
  503. else if (c == 5)
  504. return "Year ";
  505. else
  506. return "------";
  507. }
  508. }
  509.  
  510.  
  511. import java.sql.*;
  512.  
  513. /**
  514. * Created by Admin on 25.11.2016.
  515. */
  516. public class RefreshAutoIncrementForID {
  517.  
  518. Connection con;
  519. Statement stmt;
  520. ResultSet rs;
  521. String url = "", user = "", password = "";
  522.  
  523.  
  524. RefreshAutoIncrementForID(Connection con, Statement stmt, ResultSet rs, String url, String user, String password){
  525. this.con = con;
  526. this.stmt = stmt;
  527. this.rs = rs;
  528. this.url = url;
  529. this.user = user;
  530. this.password = password;
  531. }
  532.  
  533. int maxCountID = 0;
  534.  
  535. //узнаем к-тво элементов в столбце ID
  536. public int takeLengthFromId(){
  537.  
  538. String query = "SELECT max(id) from tbl1";
  539.  
  540. try {
  541. // opening database connection to MySQL server
  542. con = DriverManager.getConnection(url, user, password);
  543.  
  544. // getting Statement object to execute query
  545. stmt = con.createStatement();
  546.  
  547. // executing SELECT query
  548. rs = stmt.executeQuery(query);
  549.  
  550.  
  551. /*Вывод всей строки таблици из БД в Vector*/
  552. while (rs.next()) {
  553. maxCountID = rs.getInt(1);
  554. }
  555.  
  556.  
  557. } catch (SQLException sqlEx) {
  558. sqlEx.printStackTrace();
  559. } finally {
  560. //close connection ,stmt and resultset here
  561. try { con.close(); } catch(SQLException se) { /*can't do anything */ }
  562. try { stmt.close(); } catch(SQLException se) { /*can't do anything */ }
  563. try { rs.close(); } catch(SQLException se) { /*can't do anything */ }
  564. }
  565.  
  566. return maxCountID;
  567. }
  568.  
  569. // задаем AUTO_INCREMENT-у индекс ID с которого нужно начать добавлять id
  570. public void setIdAutoIncrement(){
  571.  
  572. String query = "alter table tbl1 auto_increment=" + ( (int)(takeLengthFromId() + 1));
  573.  
  574. try {
  575. // opening database connection to MySQL server
  576. con = DriverManager.getConnection(url, user, password);
  577.  
  578. // getting Statement object to execute query
  579. stmt = con.createStatement();
  580.  
  581. // executing SELECT query
  582. stmt.executeUpdate(query);
  583.  
  584.  
  585. } catch (SQLException sqlEx) {
  586. sqlEx.printStackTrace();
  587. } finally {
  588. //close connection ,stmt and resultset here
  589. try { con.close(); } catch(SQLException se) { /*can't do anything */ }
  590. try { stmt.close(); } catch(SQLException se) { /*can't do anything */ }
  591. try { rs.close(); } catch(SQLException se) { /*can't do anything */ }
  592. }
  593. }
  594.  
  595.  
  596.  
  597. }
  598.  
  599.  
  600.  
  601. import javax.swing.*;
  602. import java.sql.*;
  603.  
  604. /**
  605. * Created by Admin on 24.11.2016.
  606. */
  607. public class RemoveRowInMysql {
  608.  
  609.  
  610. void removeRowById(Connection con, Statement stmt, ResultSet rs, String url, String user,
  611. String password, int id){
  612. // поля для удаления строки в Mysql по Id
  613.  
  614. String queryR = "DELETE FROM tbl1 WHERE ID=" + "'" + id + "'";
  615.  
  616. try {
  617. // opening database connection to MySQL server
  618. con = DriverManager.getConnection(url, user, password);
  619.  
  620. // getting Statement object to execute query
  621. stmt = con.createStatement();
  622.  
  623. // executing SELECT query
  624. stmt.executeUpdate(queryR);
  625.  
  626.  
  627. } catch (SQLException sqlEx) {
  628. sqlEx.printStackTrace();
  629. } finally {
  630. //close connection ,stmt and resultset here
  631. try { con.close(); } catch(SQLException se) { /*can't do anything */ }
  632. try { stmt.close(); } catch(SQLException se) { /*can't do anything */ }
  633. try { rs.close(); } catch(SQLException se) { /*can't do anything */ }
  634. }
  635. }
  636. }
  637.  
  638.  
  639. import javax.swing.*;
  640. import java.awt.*;
  641.  
  642. /**
  643. * Created by Admin on 24.11.2016.
  644. */
  645. public class SizeButtons {
  646.  
  647. public void sizeBtn(JButton btnUpdate, JButton btnAdd, JButton btnRemove, JButton btnRefresh){
  648. //разммер кнопок
  649. btnUpdate.setPreferredSize(new Dimension(100, 20));
  650. btnAdd.setPreferredSize(new Dimension(100, 20));
  651. btnRemove.setPreferredSize(new Dimension(100, 20));
  652. btnRefresh.setPreferredSize(new Dimension(100, 20));
  653. }
  654. }
  655.  
  656.  
  657. import javax.swing.*;
  658. import java.sql.*;
  659.  
  660. /**
  661. * Created by Admin on 21.11.2016.
  662. */
  663. public class UpdateStringInTable {
  664.  
  665.  
  666.  
  667. public void updateValues(String url, String user, String password, JTextField field1, JTextField field2,
  668. JTextField field3,JTextField field4,JTextField field5,
  669. Connection con, Statement stmt, ResultSet rs, int fieldId ){
  670. // поля для обновления значенией в Mysql
  671.  
  672. String query1 = "update tbl1 set CODE=" + "'"+ field1.getText() +"'" + "where id="+"'"+ fieldId +"'";
  673. String query2 = "update tbl1 set TYPE=" + "'"+ field2.getText() +"'" + "where id="+"'"+ fieldId +"'";
  674. String query3 = "update tbl1 set QUANTITY=" + "'"+ field3.getText() +"'" + "where id="+"'"+ fieldId +"'";
  675. String query4 = "update tbl1 set PRICE=" + "'"+ field4.getText() +"'" + "where id="+"'"+ fieldId +"'";
  676. String query5 = "update tbl1 set YEAR=" + "'"+ field5.getText() +"'" + "where id="+"'"+ fieldId +"'";
  677.  
  678. try {
  679. // opening database connection to MySQL server
  680. con = DriverManager.getConnection(url, user, password);
  681.  
  682. // getting Statement object to execute query
  683. stmt = con.createStatement();
  684.  
  685. // executing SELECT query
  686. stmt.executeUpdate(query1);
  687. stmt.executeUpdate(query2);
  688. stmt.executeUpdate(query3);
  689. stmt.executeUpdate(query4);
  690. stmt.executeUpdate(query5);
  691.  
  692. } catch (SQLException sqlEx) {
  693. sqlEx.printStackTrace();
  694. } finally {
  695. //close connection ,stmt and resultset here
  696. try { con.close(); } catch(SQLException se) { /*can't do anything */ }
  697. try { stmt.close(); } catch(SQLException se) { /*can't do anything */ }
  698. try { rs.close(); } catch(SQLException se) { /*can't do anything */ }
  699. }
  700. }
  701.  
  702. }
  703.  
  704. import java.util.ArrayList;
  705.  
  706. /**
  707. * Created by Admin on 18.11.2016.
  708. */
  709. public class ValueInTable {
  710. Object id;
  711. Object code;
  712. Object type;
  713. Object quantity;
  714. Object price;
  715. Object year;
  716.  
  717. public ValueInTable(Object id, Object code, Object type, Object quantity, Object price, Object year){
  718. this.id = id;
  719. this.code = code;
  720. this.type = type;
  721. this.quantity = quantity;
  722. this.price = price;
  723. this.year = year;
  724. }
  725.  
  726. public ValueInTable(Object code, Object type, Object quantity, Object price, Object year){
  727. this.code = code;
  728. this.type = type;
  729. this.quantity = quantity;
  730. this.price = price;
  731. this.year = year;
  732. }
  733.  
  734. public Object getId() { return id; }
  735.  
  736. public Object getCode(){
  737. return code;
  738. }
  739.  
  740. public Object getType(){
  741. return type;
  742. }
  743.  
  744. public Object getQuantity(){
  745. return quantity;
  746. }
  747.  
  748. public Object getPrice(){
  749. return price;
  750. }
  751.  
  752. public Object getYear(){
  753. return year;
  754. }
  755.  
  756. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement