结果集:按索引检索列值与按标签检索 [英] ResultSet: Retrieving column values by index versus retrieving by label

查看:19
本文介绍了结果集:按索引检索列值与按标签检索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用JDBC时,我经常遇到像

When using JDBC, I often come across constructs like

ResultSet rs = ps.executeQuery();
while (rs.next()) {
    int id = rs.getInt(1);
    // Some other actions
}

我问自己(以及代码作者)为什么不使用标签来检索列值:

I asked myself (and authors of code too) why not to use labels for retrieving column values:

int id = rs.getInt("CUSTOMER_ID");

我听过的最好的解释是关于性能的.但实际上,它是否使处理速度极快?我不相信,尽管我从未进行过测量.即使通过标签检索会慢一点,但在我看来,它提供了更好的可读性和灵活性.
那么有人能给我很好的解释,避免通过列索引而不是列标签检索列值吗?这两种方法的优缺点是什么(也许,关于某些 DBMS)?

The best explanation I've heard is something concerning performance. But actually, does it make processing extremely fast? I don't believe so, though I have never performed measurements. Even if retrieving by label would be a bit slower, nevertheless, it provide better readability and flexibility, in my opinion.
So could someone give me good explanation of avoiding to retrieve column values by column index instead of column label? What are pros and cons of both approaches (maybe, concerning certain DBMS)?

推荐答案

您应该默认使用字符串标签.

优点:

  • 列顺序的独立性
  • 更好的可读性/可维护性

缺点:

  • 您无法控制列名(通过存储过程访问)

你更喜欢哪个?

整数?

int i = 1;  
customerId = resultSet.getInt(i++);  
customerName = resultSet.getString(i++);  
customerAddress = resultSet.getString(i++);

还是字符串?

customerId = resultSet.getInt("customer_id");  
customerName = resultSet.getString("customer_name");  
customerAddress = resultSet.getString("customer_address");

如果在位置 1 插入了一个新列怎么办?你更喜欢哪个代码?或者如果列的顺序发生变化,您需要更改哪个代码版本?

And what if there is a new column inserted at position 1? Which code would you prefer? Or if the order of the columns is changed, which code version would you need to change at all?

这就是默认情况下您应该使用字符串标签的原因.

That's why you should use string labels by default.

这篇关于结果集:按索引检索列值与按标签检索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆