Advertisement
Guest User

Java GUI Vs mysql database Part 5

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