java - 如何在不使用bean的情况下将LinkedHashMap值输入数据库?

标签 java dictionary linkedhashmap

我是 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 中按条目放置的顺序获取值。

  • 您必须确保它们始终按该顺序排列

  • 解决方案可能是您检查 key (按名称)并确定它是否是您期望的顺序/类型,以使您的解决方案更加可靠。并确保这些值将由 setString、setInt 等处理。

SQL IN 参数

  • 请记住,setString 会将所有插入操作作为 String 对象进行处理。这适用于大多数 jdbc 支持的数据库。但这并不是100%让人感到舒适。如果你知道你有整数等,那么将它们作为 setInt 处理。

来自PreparedStatement 规范:

The setter methods (setShort, setString, and so on) for setting IN parameter values must specify types that are compatible with the defined SQL type of the input parameter. For instance, if the IN parameter has SQL type INTEGER, then the method setInt should be used.

现在,这在所有数据库服务器/jdbc 驱动程序中可能并不那么严格,但值得一提的是,如果您的插入失败。

关于java - 如何在不使用bean的情况下将LinkedHashMap值输入数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30432935/

相关文章:

python 嵌套列表和字典,无法访问和设置

java - 已解析 OSGI 包上的 ClassNotFoundException

java - 如何检查文件是否正在被读取

java - OSGi 包 list 中的包类路径的字符限制?

java - 在 Java 8 中排序和分组并找到每个组的最大值

Java:通过匹配 LinkedHashMap 中的相似键来复制值

swift - 想要从 firebase 获取用户数据到字典中

python - 如何在 Python 中打印字典

Android - 如何从 Firebase 按插入顺序检索对象列表?

java - 如何将 LinkedHashMap 值加载到 Hashtable 中