[英]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.