各位大侠,你们好。我是java新手,刚刚入门。现在我有一个应用,流程如下:每隔10秒查询数据库一次,如果发现有新数据,则发起一个Socket向远程Socket服务器请求,得到返回的数据后根据返回的数据前面4位字符是否等于0000来执行下一步的数据更改动作。更改动作完成后,继续执行每隔10秒查查询数据库一次的操作同时有一点,发现有新数据则要停止每隔10秒查询数据库的操作。我是前天才开始看书学的。基础实在是太差了。请高手们指点下这个应该怎么做,附上我写的代码
import java.awt.Color;
//略public class sendData{ //创建一个新类
static JButton jbStart=new JButton("未自动提交,请点击我执行自动提交");
static JButton jbStop =new JButton("未自动提交");
static JTextPane textPane=new JTextPane();
static Socket socket;

static String driver = "com.mysql.jdbc.Driver";          // 驱动程序名
static String url = "jdbc:mysql://192.168.1.18/diandian";     // URL指向要访问的数据库名scutcs
static String user = "root";        // MySQL配置时的用户名
static String password = "";       // MySQL配置时的密码

static Connection con;
static PreparedStatement statement;
static ResultSet res;
static String sql;

public Connection getConnection() {
try {
Class.forName(driver);
con = DriverManager.getConnection(url, user, password);
            if(!con.isClosed())
             setDocs("数据库连接成功", Color.BLUE,   false,   20);     //验证是否连接成功
}catch(ClassNotFoundException e) {
setDocs("找不到数据库驱动程序", Color.red,   false,   20);
        } catch(SQLException e) {
            e.printStackTrace();
        } catch(Exception e) {
            e.printStackTrace();
        }
return con;
} public static void main(String[] args) {
sendData c = new sendData();

// TODO 自动生成方法存根
JFrame jf=new JFrame();
jf.setTitle("自动提交");
jf.setLayout(null);
Container container=jf.getContentPane(); //创建一个容器
//开始提交按钮
jbStart.setBounds(100, 10, 300,30);
container.add(jbStart);
jbStart.addActionListener(new jbActionStart());

//停止提交按钮
jbStop.setBounds(500, 10, 300,30);
container.add(jbStop);
jbStop.addActionListener(new jbActionStop());
//文本域 
setDocs("程序初始化成功", Color.BLUE,   false,   20);
textPane.setBounds(100, 50, 800,500);
container.add(textPane);

jf.setSize(1024,768);
jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
jf.setVisible(true);

con = c.getConnection();
}

static class jbActionStop implements ActionListener{
public void actionPerformed(ActionEvent arg0){
jbStart.setText("未自动提交,请点击我执行自动提交");
jbStop.setText("未自动提交");
databaseStop();
}
}

static class jbActionStart implements ActionListener{
public void actionPerformed(ActionEvent arg0){
jbStart.setText("正在自动提交!");
jbStop.setText("如需停止提交,请点击我");
databaseStart();
}
}

static void databaseStop(){
setDocs("已成功停止提交", Color.red,   false,   20);
//con.close();
}

static void databaseStart()
{
        String number;
        String jine;
    
        try {
         sql="select * from today where class_id = 1 limit 0,1";                  // 要执行的SQL语句
         statement=con.prepareStatement(sql); // statement用来执行SQL语句
            res = statement.executeQuery(sql);       // 结果集
           while(res.next()) {
             number = new String(res.getString("number"));
             jine = new String(res.getString("phone_jine"));    
                setDocs("号码:"+number+" 额度:"+jine+" 正在提交", Color.red,   false,   20);
                MyConnect(number, jine, res.getString("id"));
            }
           res.close();
        } catch(Exception e) {
            e.printStackTrace();
        }
}

static void MyConnect(String number, String jine, String id){
String serverString; StringBuilder string = new StringBuilder("2222AAAAAA");
string.append(number+"         "); //,定长20
string.append(stringRightPading(12, jine.replace(".", ""), 2)); //定长12
string.append("                    "); //合同号,定长20
string.append(stringRightPading(20, id, 2)); //流水号,定长20
String mi=KeyedDigestMD5.getKeyedDigest(string+"111111","");
string.append(mi.toUpperCase());
try{
socket=new Socket("111.111.11.22", 12321);
PrintWriter os=new PrintWriter(socket.getOutputStream());
//由Socket对象得到输入流,并构造相应的BufferedReader对象
BufferedReader is=new BufferedReader(new InputStreamReader(socket.getInputStream()));
os.print(string);
os.flush();
serverString = is.readLine();
setDocs("Client:"+string, Color.red, false,20);
setDocs("Server:"+serverString, Color.red,false,20); String isOK = serverString.substring(0, 4); if(isOK == "1111"){
        try {
         sql="update today set class_id = 2 where id="+id;           // 要执行的SQL语句
            statement=con.prepareStatement(sql); // statement用来执行SQL语句   
            statement.executeUpdate();        // 结果集
            res.close();
        } catch(Exception e) {
            e.printStackTrace();
        }
}else{
        try {
         sql="update today set class_id = 3 where id="+id;          statement=con.prepareStatement(sql);        // 结果集
         statement.executeUpdate();         } catch(Exception e) {
            e.printStackTrace();
        }
}
}catch(IOException e){
setDocs("发起Socket不成功", Color.red,   false,   20);
}
}

static void setDocs(String str, Color col, boolean bold, int fontSize){   
SimpleAttributeSet attrSet =new   SimpleAttributeSet();   
StyleConstants.setForeground(attrSet,col);   
//   颜色   
if(bold==true){
StyleConstants.setBold(attrSet,   true);   
}//   字体类型   
StyleConstants.setFontSize(attrSet,   fontSize);   
//字体大小
insert(str,attrSet);
}
static void insert(String str, AttributeSet attrSet){   
Document doc=textPane.getDocument();   
str ="\n"+str;  
try{
doc.insertString(0, str, attrSet);
}catch(BadLocationException e){   
System.out.println("BadLocationException:   "+e);   
}
}       /**
     * 右补空格或零(文字,"0",30)
     * @param strSrcLength
     * @param strSrc
     * @param flag 1: "0" 2: " " 
     * @return strReturn
     */
static String stringRightPading(int strSrcLength, String strSrc , int flag) {
       //右补空格或零的方法,略      
    }
}class KeyedDigestMD5 {
    //生成md5加密,略
}

解决方案 »

  1.   

    楼主,早上好啊
    这莫早就来发贴,很勤奋哦言归正传,感觉楼主的应用是一个典型的线程阿
    给楼主写了个思路,方法没有具体实现import java.util.*;
    public class Test3 extends Thread { /**
     * @param args
     */

    boolean status = true;     //控制线程的运行与中止的变量 Hashtable data = new Hashtable();      //从数据库查询得到的数据 void setStatus(boolean b){             //设置运行状态变量的方法
    this.status=status;
    }

    public static void main(String[] args) {
    // TODO Auto-generated method stub
    connDB();                       //连接数据库
    Test3 t = new Test3();          
    t.start();                       //启动线程
    }

    public void run(){

    while(status){ data.clear();          //把前回查询到的数据清空 data = getData();         //获取数据
     
    if(!data.isEmpty()){      //有数据的情况
    changeData(data);    //做数据更改操作
    }

    try {
    sleep(10000);      //没有数据的话,休眠10秒
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }

    }
    }

    static void connDB(){        //连接数据库的方法

    }

    static Hashtable getData(){        //获取数据的方法
    return new Hashtable();
    } static void changeData(Hashtable data){     //改变数据的方法

    }
    }