技术开发 频道

Applet连接JDBC的完整例析

【IT168 技术资源】

import java.applet.Applet; import java.awt.Graphics; import java.util.Vector; import java.sql.*; public class test extends Applet implements Runnable { private Thread worker; private Vector queryResults; private String message = "Initializing"; public synchronized void start() { // Every time "start" is called we create a worker thread to // re-evaluate the database query. if (worker == null) { message = "Connecting to database"; worker = new Thread(this); worker.start(); } } public void run() { String url = "jdbc:sybase:Tds:202.97.228.248:4100/pubs3"; String query = "select a from test"; try { Class.forName("com.sybase.jdbc.SybDriver"); } catch(Exception ex) { setError("Can't find Database driver class: " + ex); return; } try { Vector results = new Vector(); Connection con = DriverManager.getConnection(url,"sa", "great1"); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(query); while (rs.next()) { String s = rs.getString("a"); //float f = rs.getFloat("PRICE"); String text = s;// + " " + f; results.addElement(text); } stmt.close(); con.close(); setResults(results); } catch(SQLException ex) { setError("SQLException: " + ex); } } public synchronized void paint(Graphics g) { // If there are no results available, display the current message. if (queryResults == null) { g.drawString(message, 5, 50); return; } // Display the results. g.drawString("Prices of coffee per pound: ", 5, 10); int y = 30; java.util.Enumeration enum = queryResults.elements(); while (enum.hasMoreElements()) { String text = (String)enum.nextElement(); g.drawString(text, 5, y); y = y + 15; } } private synchronized void setError(String mess) { queryResults = null; message = mess; worker = null; // And ask AWT to repaint this applet. repaint(); } private synchronized void setResults(Vector results) { queryResults = results; worker = null; // And ask AWT to repaint this applet. repaint(); } }
0
相关文章