所以我有一个动态 Web 项目,它查询 MySQL 数据库并根据用户需求返回员工信息。
例如:htp://localhost:8080/Employees/123 //将返回员工 123 的信息 htp://localhost:8080/Employees //将返回所有员工的信息
问题是,如果数据库被更新并且有人要求新插入的员工,程序将抛出一个空指针。是否只有在数据库发生更改后才通知或检查更新?
这是有关 mySQL 的唯一相关代码,其余代码来自我正在使用的两个哈希映射。
package resources;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Connection;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.util.HashMap;
import pojo.Party;
public class DBConnection {
private Connection con;
private static Statement statement;
private static ResultSet resultSet;
public static DBConnection connection;
private static ResultSetMetaData meta;
private static HashMap<String,Party> map;
public Party party;
private DBConnection()
{
try
{
map = new HashMap<String,Party>();
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(//not relevant, assume this works);
statement = con.createStatement();
readData();
}
catch (Exception e)
{
System.out.print("Error: "+e);
}
}
public void readData()
{
try
{
String query = "(SELECT * FROM PureServlet)";
resultSet = statement.executeQuery(query);
meta = resultSet.getMetaData();
String columnName, value, partyName;
while(resultSet.next())
{
partyName = resultSet.getString("PARTY_NAME");
map.put(partyName, new Party()); //this is the map that keeps track of all parties
party = map.get(partyName);
//getColumn...() irritatingly starts at 1 and not 0 thus j=1
for(int j=1;j<=meta.getColumnCount();j++)
{
columnName = meta.getColumnLabel(j);
value = resultSet.getString(columnName);
party.getPartyInfo().put(columnName, value); //this is the hashmap within the party that keeps
//track of the individual values. The column Name = label, value is the value
}
}
}
catch (Exception e)
{
System.out.println(e);
}
}
public static HashMap<String,Party> getPartyCollection()
{
if(connection == null)
{
connection = new DBConnection();
}
return map;
}
}