【发布时间】:2013-03-05 02:06:58
【问题描述】:
我有一个作为字符串获得的参数
String Dept_ID[] = request.getParameterValues("dept_id"))
在jsp中。我必须在类型为数字的数据库中插入字符串
@DEPT_ID NUMERIC(10,0)).
如何进行转换?
【问题讨论】:
标签: java string integer type-conversion
我有一个作为字符串获得的参数
String Dept_ID[] = request.getParameterValues("dept_id"))
在jsp中。我必须在类型为数字的数据库中插入字符串
@DEPT_ID NUMERIC(10,0)).
如何进行转换?
【问题讨论】:
标签: java string integer type-conversion
您的代码正在接收一个 array 字符串。您可以根据需要使用Integer.parseInt 或Long.parseLong 将数组中的条目转换为数字。
例如:
String Dept_ID[] = request.getParameterValues("dept_id"));
int[] ids = null;
if (Dept_ID != null) {
ids = new int[Dept_ID.length];
for (int index = 0; index < Dept_ID.length; ++index) {
ids[index] = Integer.parseInt(Dept_ID[index]);
}
}
如果数字使用与 10 不同的基数(数字基数),您可以提供基数作为第二个参数(有关详细信息,请参阅链接)。
【讨论】:
ServletRequest#getParameterValues 与数据库没有任何关系。 (如果 request 不是 ServletRequest 或它的子类,您真的需要这么说,因为这是我们可以做出的唯一合理假设。)
上面的答案是正确的,但它没有考虑当您将字母作为无法转换的输入时会发生什么。如果你问我,你想对那部分使用 try and catch 方法。
类似的东西(假设您使用上面的代码):
String Dept_ID[] = request.getParameterValues("dept_id"));
int[] ids = null;
if (Dept_ID != null) {
ids = new int[Dept_ID.length];
for (int index = 0; index < Dept_ID.length; index++) {
try {
ids[index] = Integer.parseInt(Dept_ID[index]);
}
catch ( NumberFormatException e ) {
System.out.println("Invalid crap.");
}
}
}
另外请注意,我将 ++index 部分放在 index++ 的另一边,如果你不这样做,你将一直丢失数组中的第一个索引。
【讨论】: