How save the serial COMport value in mysql databse. Following code is here.
package simpleread; import java.io.*; import java.sql.Connection; import java.sql.PreparedStatement; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; import javax.comm.*; public class SimpleRead implements Runnable, SerialPortEventListener { static CommPortIdentifier portId; static Enumeration portList; 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("COM18")) { // if (portId.getName().equals("/dev/term/a")) { SimpleRead reader = new SimpleRead(); } } } } 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(100, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); } catch (UnsupportedCommOperationException e) {System.out.println(e);} readThread = new Thread(this); readThread.start(); } @Override public void run() { try { Thread.sleep(60000); } catch (InterruptedException e) {System.out.println(e);} } @Override 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[1024]; int[] readBuffer1 = new int[1024]; int m=0; try { while (inputstream.available() > 0) { int numBytes=0; readBuffer1[m] =inputstream.read((readBuffer)); System.out.println(new String(readBuffer)); //System.out.println(inputstream); try { Thread.sleep(6000); } catch (InterruptedException ex) { Logger.getLogger(SimpleRead.class.getName()).log(Level.SEVERE, null, ex); } try { Connection con=(Connection) ConnectionFactory.getConnection(); System.out.println(con); String sql= "insert into Read2(DTST) Values(?)"; PreparedStatement ps=con.prepareStatement(sql); ps.setInt(1,readBuffer1[m]); ps.executeUpdate(); // System.out.println(""+numBytes); // System.out.print(new String(readBuffer)); System.out.println((readBuffer1[m])); // System.out.println(new String(readBuffer, "US-ASCII")); m++; } catch(Exception e) { } } } catch (IOException e) {System.out.println(e);} break; } } }
plz help.
Ads