[英]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。
// 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中獲取值, 並按放置條目的順序進行 。
您將必須確保始終按順序排列它們 。
一個解決方案可能是您檢查密鑰(按名稱)並確定它是否是期望的順序/類型,以使您的解決方案更可靠。 並確保將使用setString,setInt等對待這些值。
根據PreparedStatement規范:
用於設置IN參數值的setter方法(
setShort
,setString
等) 必須指定與輸入參數的已定義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.