如何将java对象转换为insert sql语句? [英] How can convert a java object into insert sql statement?

查看:82
本文介绍了如何将java对象转换为insert sql语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这样的事情:

Something like this:

public void convert(Category cat)
{
//convert cat into string sql "insert into category() values()"  
 
}

推荐答案

简单易用的方法 toString()在你的Category类中,你不需要创建任何方法将Java Object转换为SQL String。
Easy way to use "toString()" in your Category Class, and you don't need to create any method to convert Java Object into SQL String.


解决看看这段代码由我自己创建



solved look this code create by myself

Autos aut=new Autos();
       aut.setAuto("Auto1");
       aut.setColor("Negro");
       aut.setId_auto(12);
       aut.setPeso(10000);
       aut.setTama("Grande");

   Field[] fields = aut.getClass().getDeclaredFields();
   String campos="";
   String valores="";
   for (int i = 0; i < fields.length; i++) {
      try{

           String name = fields[i].getName();
           String value = fields[i].get(aut).toString();
           if(i!=0){
               campos=campos+",";
               valores=valores+",";
           }
           if(fields[i].get(aut) instanceof String){
               valores=valores+"'"+value+"'";
           }
           else{
               valores=valores+value;
            }
           campos=campos+name;
       } catch (IllegalAccessException ex) {}
   }
     String sql="insert into dbo."+aut.getClass().getSimpleName().toLowerCase()+"("+campos+")values("+valores+");";
     System.out.println(sql);


这篇关于如何将java对象转换为insert sql语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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