20780

MySql expected output not coming

Question:

So I have this program which reads serial Input from COM port and places it in MySql database named asset.

Code:

import java.io.*; import java.util.*; import gnu.io.*; import java.sql.*; public class SimpleRead implements Runnable, SerialPortEventListener { static CommPortIdentifier portId; static Enumeration portList; static Connection con=null; static String url = "jdbc:mysql://localhost:3306/track"; static String uid="root"; static String pwd="root"; InputStream inputStream; SerialPort serialPort; Thread readThread; public static void main(String[] args) { portList = CommPortIdentifier.getPortIdentifiers(); while (portList.hasMoreElements()) { portId = (CommPortIdentifier) portList.nextElement(); if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) { if (portId.getName().equals("COM1")) { // if (portId.getName().equals("/dev/term/a")) { SimpleRead reader = new SimpleRead(); try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection(url,uid,pwd); } catch(Exception s){ System.out.println(s); } } } } } public SimpleRead() { try { serialPort = (SerialPort) portId.open("SimpleReadApp", 2000); } catch (PortInUseException e) {System.out.println(e);} try { inputStream = serialPort.getInputStream(); } catch (IOException e) {System.out.println(e);} try { serialPort.addEventListener(this); } catch (TooManyListenersException e) {System.out.println(e);} serialPort.notifyOnDataAvailable(true); try { serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); } catch (UnsupportedCommOperationException e) {System.out.println(e);} readThread = new Thread(this); readThread.start(); } public void run() { try { Thread.sleep(20000); } catch (InterruptedException e) {System.out.println(e);} } public void serialEvent(SerialPortEvent event) { switch(event.getEventType()) { case SerialPortEvent.BI: case SerialPortEvent.OE: case SerialPortEvent.FE: case SerialPortEvent.PE: case SerialPortEvent.CD: case SerialPortEvent.CTS: case SerialPortEvent.DSR: case SerialPortEvent.RI: case SerialPortEvent.OUTPUT_BUFFER_EMPTY: break; case SerialPortEvent.DATA_AVAILABLE: byte[] readBuffer = new byte[20]; try { while (inputStream.available() > 0) { int numBytes = inputStream.read(readBuffer); } System.out.print(new String(readBuffer)); } catch (IOException e) {System.out.println(e);} Statement st=null; try{ st=con.createStatement(); } catch(Exception ex) { System.out.println(ex); } try{ String idd = new String(readBuffer); String query = "INSERT INTO asset (id) VALUES(?)"; PreparedStatement pstm = con.prepareStatement(query); pstm.setString(1, idd); pstm.executeUpdate(); pstm.close(); con.close(); //st.executeUpdate("insert into asset(id) VALUES('"+idd+"'"); //con.close(); } catch(Exception ex){ System.out.println(ex); } break; } } }

So whenever the data is recieved from the COM port, an entry is created by the above code in mysql table.

<strong>The expected entry should be something like :</strong>

<img alt="Expected Image" class="b-lazy" data-src="https://i.stack.imgur.com/QDkTS.png" data-original="https://i.stack.imgur.com/QDkTS.png" src="https://etrip.eimg.top/images/2019/05/07/timg.gif" />

<strong>What actual output i get :</strong>

<img alt="Real Image" class="b-lazy" data-src="https://i.stack.imgur.com/RQ2fS.png" data-original="https://i.stack.imgur.com/RQ2fS.png" src="https://etrip.eimg.top/images/2019/05/07/timg.gif" />

What actually happens is that One input from com port is creating two entries into the table one with the serial input and timestamp and one only with the timestamp.

What I want to achieve is that only 1 entry per COM input. Like the expected Image.

Answer1:

Check ID before inserting it into the database -

String idd = new String(readBuffer); if(!idd.equals("") || !idd.equals(null)){ String query = "INSERT INTO asset (id) VALUES(?)"; PreparedStatement pstm = con.prepareStatement(query); pstm.setString(1, idd); pstm.executeUpdate(); pstm.close(); con.close(); }

Recommend

  • How to get multi line result from serial port
  • CommPortIdentifier.getPortIdentifiers with zero ports on Linux
  • NoSuchPortException using RXTX Java library on Windows?
  • Click on button in another program - FindWindow, C#
  • C++ friend class std::vector
  • How to get listview position?
  • Regarding starting the threads on a condition
  • How to access profile picture with Facebook API in Swift 3?
  • How to use jQuery's $.post() method with async/await and typescript
  • Scipy Leastsq Optional Output Variable (Mesg)
  • Question about instantiating object
  • Subclassing QGraphicsItem prevents me from being able to use itemAt() on a QGraphicsScene/View
  • Angularjs pass function from Controller to Directive (or call controller function from directive) -
  • Checking if an array in C is symmetric
  • c# open webrowser in many tab
  • Bypass multiple inheritance in Java
  • how to find common suffix in java by using method
  • Display java JPanel in a JFrame
  • onBackPressed() not being executed
  • How to Cache Real-time Data?
  • iOS: Detect app start via notification press
  • how to adjust image in a panel in Java swing?
  • How to access EntityManager inside Entity class in EJB3
  • how to do an event when i swipe from fragment to the other
  • Spring Data JPA custom method causing PropertyReferenceException
  • JFileChooser in front of fullscreen Swing application
  • HTML download movie download link
  • How to draw moving and Running sine wave chart using JFree chart in java?
  • Possible to stop flickering java tooltip in heavyweight mode?
  • output of program is not same as passed argument
  • sending/ receiving email in Java
  • Eraser for UIBezierPath
  • Akka Routing: Reply's send to router ends up as dead letters
  • Suggestions to manage Login/Logout transitions
  • Exception on Android 4.0 `android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode)`
  • unknown Exception android
  • EntityFramework adding new object to nested object collection
  • Checking variable from a different class in C#
  • failed to connect to specific WiFi in android programmatically
  • How can I use threading to 'tick' a timer to be accessed by other threads?