我想编写一个执行不同查询的函数。我希望它传递表名和select,insert的方法,以及关于where之类的值列表。我在php中做了类似的事情,我处理了数组中的所有内容,但是不知道如何在Java中解决,可能还有一些现成的类?
我目前的PHP解决方案:
$user = db::getInstance()->update('users', 2, array(
'password' => 'newpassword'));
public function update($table, $id, $fields){
$set = '';
$x = 1;
foreach($fields as $name => $value){
$set .= "{$name} = ?";
if($x < count($fields)){
$set .= ', ';
}
}
$sql = "UPDATE {$table} SET {$set} where id = {$id}";
if(!$this->query($sql, $fields)->error()){
return true;
}
}
答案 0 :(得分:2)
您可以使用接口并将该接口的实施作为参数传递
来做同样的事情一个抽象的例子:
界面
public interface MyInterface {
public void doTheSelect();
}
实施A
public class MyImplementationA implements MyInterface{
@Override
public void doTheSelect() {
// Do some sort of select
}
}
实施B
public class MyImplementationB implements MyInterface{
@Override
public void doTheSelect() {
// Do some other sort of select
}
}
您的班级与您的功能/方法
public class MyClass{
public void myFunction(MyInterface implementation) {
implementation.doTheSelect();
}
}
“差异”是,您必须认为面向对象
答案 1 :(得分:1)
这是我的解决方案
@Override
public int insert(Map<String, String> valueMap, String table) throws SQLException {
// TODO Auto-generated method stub
Connection conn = Database.getInstance().getConnection();
String val = "";
String query = "";
String question = "";
Integer mapsize = valueMap.size();
Integer x = 1;
for (Map.Entry<String, String> entry : valueMap.entrySet()) {
val += entry.getKey();
question += "?";
if (x < mapsize) {
val += ", ";
question += ", ";
}
mapsize--;
}
query = "insert into " + table + "(" + val + ") values ("+question+")";
PreparedStatement add = conn.prepareStatement(query);
for(Map.Entry<String, String> entry : valueMap.entrySet()){
add.setObject(x,entry.getValue());
x+=1;
}
int addtotable = add.executeUpdate();
add.close();
return addtotable;
}