大家都进来看看,这两种方案哪个可行?哪个效率更高?

场景描述:

大伙不都搞数据库嘛,数据库里总要设置参数的吧?嗯,对,这两个方案就是设置参数用的。
我不是一直搞.net的嘛,所以对SqlHelper有好感,这两种实现就是其中的一个方法。

方案一:(这个是我在网上找到的)

/**
* @param pstmt
* @param cmdtext
* @param params
* Object[]
* @throws Exception
*/
private static void prepareCommand(PreparedStatement pstmt, Object[] params) throws Exception
{
if(params == null || params.length == 0)
{
return;


}
for (int i = 0; i < params.length; i++)
{
try
{
pstmt.setDate(i + 1, java.sql.Date.valueOf(params[i]));
}
catch (Exception e)
{
try
{
pstmt.setDouble(i + 1, Double.parseDouble(params[i]));
}
catch (Exception e1)
{
try
{
pstmt.setInt(i + 1, Integer.parseInt(params[i]));
}
catch (Exception e2)
{
try
{
pstmt.setString(i + 1, params[i]);
}
catch (Exception e3)
{
System.out.print("SQLHelper-PrepareCommand Err1:" + e3);
}
}
}
}
}
}



方案二:(这个是我写的,因为我感觉那么多try...catch简直要摧毁我的意志,虽然反射也很费吧……)

/**
*
* @param pstm
* @param params
*/
public static void prepareCommand(PreparedStatement pstm,Object[] params)
{
if(params == null || params.length == 0)
{
return;
}

try
{
for(int i = 0;i < params.length;i++)
{
int parameterIndex = i + 1;
//String
if(params[i].getClass() == String.class)
{
pstm.setString(parameterIndex, params[i].toString());
}
//Short
else if(params[i].getClass() == short.class)
{
pstm.setShort(parameterIndex, Short.parseShort(params[i].toString()));
}
//Long
else if(params[i].getClass() == long.class)
{
pstm.setLong(parameterIndex, Long.parseLong(params[i].toString()));
}
//Integer
else if(params[i].getClass() == Integer.class)
{
pstm.setInt(parameterIndex, Integer.parseInt(params[i].toString()));
}
//Date
else if(params[i].getClass() == Date.class)
{
java.util.Date dt = (java.util.Date)params[i];
pstm.setDate(parameterIndex, new java.sql.Date(dt.getTime()));
}
//Byte
else if(params[i].getClass() == byte.class)
{
pstm.setByte(parameterIndex, (Byte)params[i]);
}
//Float
else if(params[i].getClass() == float.class)
{
pstm.setFloat(parameterIndex, Float.parseFloat(params[i].toString()));
}
//Boolean
else if(params[i].getClass() == boolean.class)
{
pstm.setBoolean(parameterIndex, Boolean.parseBoolean(params[i].toString()));
}
else
{
throw new Exception("参数准备出错:数据类型不可见" + params[i].getClass().toString());
}
}
}
catch(Exception e)
{
}
}

你可能感兴趣的:(Java,笑话,SQL,.net)