[英]Java exception when adding to map
不知道出什么问题了...它应该可以工作,或者可能丢失了某些东西? 以下是代码:
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>();
它应该运行良好。
您在哪里初始化“地图”? 在我看来是空的。
更改此行:
static TreeMap<String, Integer> map = new TreeMap<String, Integer>();
您对此进行声明并将其设置为null,但是我看不到在哪里使用它。
PreparedStatement insertMap = null;
您在这里还有更多的心痛:
Connection con=null;
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection(
"jdbc:oracle:thin:@oXXX",
"XXX",
"XXX");
con.setAutoCommit(false);
向下移动autoCommit,直到从驱动程序管理器获得连接为止。
您要序列化地图以将其插入数据库吗? 这没有被标准化。 规范化的架构每个条目将有一行。
我阅读您的代码越多,它的意义就越小。 祝好运。
您永远不会初始化map
到任何东西,因此它为null
。 您需要在某处为其分配有效的TreeMap<String, Integer>
,例如在声明它的第2行,例如,使用:
static TreeMap<String, Integer> map = new TreeMap<String, Integer>();
变量映射永远不会初始化,仅在构造函数中声明。
map = new TreeMap<String, Integer>();
您只声明地图,而不初始化它
static TreeMap<String, Integer> map=new HashMap<String,Integer>();
static TreeMap<String, Integer> map = new TreeMap<String, Integer>(); // <-- in your code, you're not constructing it
static TreeMap<String, Integer> localMap = new TreeMap<String, Integer>();
您可以初始化变量Connection con = null; 然后我们设置con.setAutoCommit(false)..如果不为此创建对象,如何设置自动提交呢?
您确实在声明时初始化了map对象,就像您在声明时初始化了localMap对象一样,只是检查了
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.