【发布时间】:2015-01-28 15:39:28
【问题描述】:
我创建了一个 java applet 类,它从 db 中读取数据,然后在 applet 中显示。该程序运行正确,当我从 Eclipse IDE 运行它时,我会获取数据,但是当我使用 html 代码从浏览器运行它时,它会运行但不会从数据库中获取数据。这是我使用的代码。
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;
import javax.swing.JApplet;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.JLabel;
public class Driver extends JApplet {
private Connection connect = null;
private Statement statement = null;
private PreparedStatement preparedStatement = null;
private ResultSet resultSet = null;
private JLabel lbl = null;
private String label;
public void init() {
try {
try {
// this will load the MySQL driver, each DB has its own driver
Class.forName("com.mysql.jdbc.Driver");
// setup the connection with the DB.
connect = DriverManager
.getConnection("jdbc:mysql://localhost/jdbc?"
+ "user=root&password=");
// statements allow to issue SQL queries to the database
statement = connect.createStatement();
// resultSet gets the result of the SQL query
resultSet = statement
.executeQuery("select * from jdbc.info");
// writeResultSet(resultSet);
while (resultSet.next()) {
String user = resultSet.getString("id");
String name = resultSet.getString("name");
label = user +" "+ name;
}
} catch (Exception e) {
throw e;
} finally {
// close();
}
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
lbl = new JLabel(label);
add(lbl);
}
});
} catch (Exception e) {
System.err.println("createGUI didn't complete successfully");
}
}
public static void main(String[] args) throws Exception {
Driver dao = new Driver();
dao.init();
}
}
这是 HTML 代码
<html>
<head>
<title>My first app reding from db</title>
</head>
<body>
My first app reding from db<br />
<applet code="jdbcdemo/Driver.class" width="700" height="700" />
</body>
</html>
谁能帮我找出为什么小程序没有从本地 wamp 服务器上的数据库中读取。它们是我必须添加 .Class 才能运行的特定目录吗?
【问题讨论】:
-
您遇到什么错误?连接字符串中的localhost不正确,应该是数据库服务器的IP地址或域名,localhost会指向client-machine,肯定不是db-server。如果有人在服务器上浏览小程序(实际坐着),这将是一种特殊情况
-
它没有给出任何错误,它只是不显示数据。我只是尝试更改它并添加了我的服务器 IP,但它仍然不起作用。
-
在启动小程序之前使用
e.printStacktrace();就在throw e;下并打开Java 控制台(我认为是从控制面板) -
如@Yazan 所述。确保Java Console 配置为显示。如果默认级别没有输出,提升级别再试一次。
-
@Yazan 不确定提供对数据库的外部访问是否是个好主意,我更喜欢一些非常简单的服务,可以配置为提供一些基本的安全性。