精华区 [关闭][返回]

当前位置:网易精华区>>讨论区精华>>编程开发>>● Java>>JAVA编程>>数据库接口>>完整JDBC例子(jconnect3.0)

主题:完整JDBC例子(jconnect3.0)
发信人: ago()
整理人: hht(1999-03-11 11:47:11), 站内信件
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();
    }
}

--
     /
O===||==================>
     \
ago

※ 来源:.网易虚拟社区 club.netease.com.[FROM: 202.97.228.200]

[关闭][返回]