簡體   English   中英

如何在不使用bean的情況下將LinkedHashMap值輸入數據庫?

[英]How to enter LinkedHashMap Values to database without using bean?

我是LinkedHashMap的新手。

現在我有一些LinkedHashMap的數據,例如-

article_ID=386247568292, author_externalId=235697849816687, author_fbid=235697849816687, ...

現在這是我的數據庫輸入代碼

public void InsertEntry(LinkedHashMap<String, Object> entMap) throws SQLException {

    Connection conn = null;
    PreparedStatement pstmt = null;

    conn = pool.getConnection();
    String sql="INSERT into socialmedia(article_ID,author_externalId, author_fbid)"
                + "VALUES(?,?,?)";
   pstmt = conn.prepareStatement(sql);

現在如何將My LinkedHashMap值輸入字符串,以便可以將所有這些值輸入數據庫。

我不想使用任何Bean。

從LinkedHashMap獲取值

// either you loop thru the entries
Set<String> keys = entMap.keySet();
int param = 1;
for(String k:keys) {
    pstmt.setString( (param++), (String)entMap.get(k) );
}

or

// if you prefer use the key names, e.g.
String aid = (String) entMap.get("article_ID");

關於LinkedHashMap

  • 請記住,您將從LinkedHashMap中獲取值, 並按放置條目的順序進行

  • 您將必須確保始終按順序排列它們

  • 一個解決方案可能是您檢查密鑰(按名稱)並確定它是否是期望的順序/類型,以使您的解決方案更可靠。 並確保將使用setString,setInt等對待這些值。

SQL IN參數

  • 請記住,setString將所有插入內容作為String對象處理。 這將適用於大多數受jdbc支持的數據庫。 但這並不是百分百舒適。 如果您知道有整數等,則將它們作為setInt處理。

根據PreparedStatement規范:

用於設置IN參數值的setter方法( setShortsetString等) 必須指定與輸入參數的已定義SQL類型兼容的類型。 例如,如果IN參數的SQL類型為INTEGER,則應使用setInt方法。

現在,在所有數據庫服務器/ jdbc驅動程序中這可能不是很嚴格,但是如果插入失敗,則值得一提。

下面應該工作....

public void InsertEntry(LinkedHashMap<String, Object> entMap) throws SQLException {
    Connection conn = null;
    PreparedStatement pstmt = null;
    conn = pool.getConnection();
    String sql="INSERT into socialmedia(user_name,article_count,epoch,description,authorId,article_url,publish_date,harvest_date,following,followers,updates,sentiment)"
            + "VALUES(?,?,?,?,?,?,?,?,?,?,?,?)";
    pstmt = conn.prepareStatement(sql);
    Set keys = entmap.keySet();  
    int rowId=1;
    for(String key : keys)
    {
       String val = entMap.get(key);
       pstmt.setString(rowId,val);
       rowId++;
    }
    pstmt.executeUpdate();
}

請讓我知道,如果你有任何問題。

謝謝大家的答復。 我做到了-

String sql = "INSERT INTO students(article_ID, description_charset, author_appScopedId, author_externalId) values(?,?,?,?);
pstmt = conn.prepareStatement(sql);

pstmt.setString(1, (String) entMap.get("article_ID"));
pstmt.setString(2, (String) entMap.get("description_charset"));
pstmt.setString(3, (String) entMap.get("author_appScopedId"));
pstmt.setString(4, (String) entMap.get("author_externalId"));

pstmt.executeUpdate();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM