2017-09-13 79 views
-2

我想問問如何將多維數組存儲到MySQL數據庫。 例如我具有(X,Y)的陣列如何在java中將多維數組值存儲到MySQL數據庫中?

array[][] = { 
{3, 10}, 
{2, 11}, 
{4, 9}, 
} 

我試圖使用preparedStatement時SETINT存儲這些值來MySQL數據庫但輸出原來是這樣的:

java.lang.ArrayIndexOutOfBoundsException: 3 

這是代碼:

import java.sql.*; 
import java.util.logging.Level; 
import java.util.logging.Logger; 

public class InsertDB { 

    public static void main(String[] args) { 
     Connection conn = null; 
     Statement exe = null; 



    int[][] multiarray = { 
       {3, 10}, 
       {2, 11}, 
       {4, 9}, 
      }; 

     try { 
      Class.forName("com.mysql.jdbc.Driver"); 
      System.out.println("Connecting to the database"); 
      conn = DriverManager.getConnection("jdbc:mysql://localhost/finalproject","root",""); 
      System.out.println("Database connected"); 
      exe = conn.createStatement(); 

      conn.setAutoCommit(false); 
      PreparedStatement stmt = null; 
      stmt = conn.prepareStatement("INSERT INTO SIGNATURE (angle, distance) VALUES (?,?)"); 
      for (int i = 0; i < 10; i++) { 
       stmt.setInt(1, multiarray[i][0]); 
       stmt.setInt(2, multiarray[i][1]); 
       stmt.addBatch(); 
      } 

      stmt.executeBatch(); 
      conn.commit(); 

      System.out.println("Data added ! "); 
     } catch (ClassNotFoundException ex) { 
      Logger.getLogger(InsertDB.class.getName()).log(Level.SEVERE, null, ex); 
     } catch (SQLException ex) { 
      Logger.getLogger(InsertDB.class.getName()).log(Level.SEVERE, null, ex); 
     }finally{ 
      try{ 
       if (exe != null) 
        conn.close(); 
      }catch (SQLException se){ 

      }try{ 
       if(conn != null) 
        conn.close(); 
      }catch(SQLException se){ 

      } 
    } 
     System.out.println("Done !"); 
    } 

} 

有人能解決這個問題,

謝謝:)

+0

'有人可以解決這個問題'不除非你顯示的代碼失敗... – marekful

+0

**陣列指數出界:** *** 3 *** – nullpointer

+0

你可以請分享你的代碼? –

回答

0

您可以將數組轉換爲字符串,然後您可以保存。

0

異常的堆棧跟蹤最有可能的點進去for循環和異常恕我直言相當精確地解釋了這個問題:

你的陣列multiarray具有3x2的元素,即multiarray[0..2][0..1]。在你的循環中,你迭代i到10,並嘗試訪問multiarray[3][0] - 因爲3是一個無效的索引,你會得到相應的異常,IndexOutOfBoundsException

確保你不會進一步遍歷比你的數組的大小和你的代碼工作正常:

for (int i = 0; i < multiarray.length; i++) { 
    stmt.setInt(1, multiarray[i][0]); 
    stmt.setInt(2, multiarray[i][1]); 
    stmt.addBatch(); 
    } 

BTW:你的問題意味着你想一個多維數組存儲到一個單一的數據庫字段。這在某些情況下可能是有意義的,但是這種情況很罕見,並且對它的支持很差或不標準化。

您所展示的代碼並不是真的將多維數組存儲到數據庫中 - 您將單個整數存儲到數據庫表中。多維數組只是數據庫表中數據在Java中的表示形式。

你可能想澄清你的問題。

+0

之上添加了我的代碼,感謝您的回覆。我試圖改變循環multiarray.length,但它沒有奏效,它給出了和以前一樣的異常。上面的數組僅僅是一個例子。實際上我正在圖像處理中進行形狀檢測。特徵提取的輸出是包含圖像對象的{角度,距離}的多維數組。我想插入這些值到數據庫,所以我可以檢索到其他操作。你有什麼解決方案嗎?以前感謝:) – user2738592

相關問題