我一直在用Java编写一个应用程序来检查SQL数据库中的某些信息,然后根据读取的值来采取不同的行为,我试图让软件无限循环,因此每次都会动作新信息将添加到数据库中。该软件用于在将ZPL条形码标签添加到SQL数据库时将其打印出来。我希望程序处于一个常量循环中,检查是否添加了新的ProcessDate,我的代码如下。任何帮助appriciated;
package com.company;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.sql.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class SqlCon
{
public static void main(String[] args)
{
// Connects too SQL database
String connectionString = "jdbc:sqlserver://acstdevsql01:1433;database=brad;user=USER;password=PW;";
// Selects data from database
String SQL = "SELECT TOP 2 [PK_PrintQueueID],[FK_PrinterID],[FK_BarcodeTypeID],[Barcode],[Quantity],[QueueDate],[ProcessedDate] FROM [Brad].[dbo].[PrintQueue] -- WHERE ProcessedDate IS NULL";
// Declare variable connection.
Connection connection = null;
// Set date format
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// Get current date time with Date()
Date date = new Date();
try
{
connection = DriverManager.getConnection(connectionString);
Statement stmt = connection.createStatement();
Statement stmt2 = null;
ResultSet rs = stmt.executeQuery(SQL);
while (rs.next())
{
String FK_BarcodeTypeID = rs.getString("FK_BarcodeTypeID");
// Get barcode value to split form SQL result set
String barcode = rs.getString("Barcode");
String[] parts = barcode.split("-");
// First half of barcode
String part1 = parts[0];
// Set the processed date on any item which does not already have one set, The systems current time/date is used
String SQL2 = "UPDATE PrintQueue SET ProcessedDate = '"+dateFormat.format(date)+"' WHERE PK_PrintQueueID = '"+rs.getString("PK_PrintQueueID");
// Actions for serialized barcode (FK_BarcodeTypeID = 1)
if (FK_BarcodeTypeID.equals("1"))
{
// ^BC = Type 128 barcode
String zpl = "^XA^BY3,3,140^FT60,200^BCN,Y,N,N^FD>:"+rs.getString("Barcode")+"^FS^FT200,250^A0N,42,40^FH^FD"+part1+"^FS^XZ";
printlabel(zpl);
System.out.println(rs.getString("Barcode"));
}
// Actions for unserialized barcode (FK_BarcodeTypeID = 2)
else
{
// ^B3 = Type 30 barcode
String zpl = "CT~~CD,~CC^~CT~ ^XA~TA000~JSN^LT0^MNW^MTT^PON^PMN^LH0,0^JMA^PR4,4~SD15^JUS^LRN^CI0^XZ^XA^MMT^PW674^LL0376 ^LS0 ^BY2,3,151^FT84,249^BCN,,Y,N^FD>:P-GEN-SEA-BOX2ULTYPE^FS ^PQ1,0,1,Y^XZ";
printlabel(zpl);
System.out.println(rs.getString("Barcode"));
}
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public static void printlabel(String zpl)
{
try
{
Socket clientSocket;
clientSocket = new Socket("IP", PORT);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
outToServer.writeBytes(zpl);
clientSocket.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
答案 0 :(得分:0)
不是这样,一个永恒的问题。如果数据库可以在触发器上调用java代码,那会没什么用。 MS SQL Server AFAIK无法使用。
所以你需要一个定时器控制" cron"询问是否有工作要做的工作。如果你有其他批处理工作要做,比如在深夜,java中的cron库可能没问题。搜索cron,quartz,scheduler,timer。
(消息队列可以替代。)