不确定出了什么问题...它应该可以工作,或者可能缺少某些东西?代码如下:
public class TestOracleMap implements java.io.Serializable{
static TreeMap<String, Integer> map;
static TreeMap<String, Integer> localMap = new TreeMap<String, Integer>();
public static void StoreMapInDB(TreeMap<String, Integer> map) throws
IOException, FileNotFoundException{
try {
PreparedStatement insertMap = null;
//String insertString = "INSERT INTO TESTMAP(ID, MPFIELD) VALUES (1, ?)";
Connection con=null;
con.setAutoCommit(false);
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection(
"jdbc:oracle:thin:@oXXX",
"XXX",
"XXX");
ByteArrayOutputStream bos = new ByteArrayOutputStream() ;
ObjectOutputStream out = new ObjectOutputStream(bos);
out = new ObjectOutputStream(bos) ;
out.writeObject(map);
out.close();
byte[] buf = bos.toByteArray();
PreparedStatement prepareStatement = con.prepareStatement("insert into
TESTMAP(ID,MAPFIELD)values(?,?)");
prepareStatement.setLong(1, 1);
prepareStatement.setBinaryStream(2, new ByteArrayInputStream(buf), buf.length);
// insertMap.executeUpdate();
con.commit();
} catch(Exception e){e.printStackTrace();}
}
public static void main(String[] args)
{
try{
DateTime today = new DateTime();
int x = 1;
map.put("Hello!", x);
StoreMapInDB(map);
}catch(IOException ioe){
System.err.print(ioe);
}
}
}
错误出现在 main 方法中的行中,即:
map.put("Hello!", x);
它给出:
Exception in thread "main" java.lang.NullPointerException
at core.smd.classes.TestOracleMap.main(TestOracleMap.java:61)
Java Result: 1
最佳答案
似乎您从未实例化map
。您在这里声明
static TreeMap<String, Integer> map;
但是当你在这里使用它时,它仍然是null
,给你NullPointerException
。
map.put("Hello!", x);
如果您之前这样做过
map = new TreeMap<String, Integer>();
它应该运行良好。
关于添加到 map 时Java异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8413544/