java两种方式操作数据库

因为一个项目学习了另外的方式去操作数据库在这里比较一下。

方式框架

第一种

在这里插入图片描述
需要添加注解@Repository并且需要在查询的时候

@Query(value = "SELECT * FROM 表名 WHERE id  = :id", nativeQuery = true)
    表中字段的实体 findByID(@Param("id") String id);

Param注解的就是:id要求能够对应上,Query注解中value 后面直接加对应的查询sql,参数使用上一个方式进行注入

启动类扫描时候需要添加EnableJpaRepositories
在这里插入图片描述

第二种
    @PersistenceContext
    private EntityManager entityManager;
 String  sql = "select count(*) from user_tables where table_name =upper('"+tablenameNew+"')";
            javax.persistence.Query query = entityManager.createNativeQuery(sql);
            query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
            List<Map> rows = query.getResultList();

但是使用时候一定要添加注解@Transactional @Modifying

增加

第一种
 @Transactional
    @Modifying
    @Query(value = "insert into GSGUOXIN_PUSHED(id,DJBH,DJWCSj,filename,fileid) values(:id,:DJBH,to_timestamp(:DJWCSj, 'YYYY-MM-DD hh24:mi:ss'),:filename,:fileid)", nativeQuery = true)
    void addGuoXinPush(@Param("id") String id, @Param("DJBH") String DJBH, @Param("DJWCSj") String DJWCSj, @Param("filename") String filename, @Param("fileid") String fileid );

第二种
    //新表的插入操作
    @Transactional
    @Modifying
    public JSONObject insertIntotablenameNew(List<Map> rows,String tablenameNew,String datagovernancetype) {
        try{
            StringBuilder rowsName = new StringBuilder();
            StringBuilder rowsValue = new StringBuilder();

            for (int i = 0; i < rows.size(); i++) {
                Map map = rows.get(i);
                for (Object o : map.keySet()) {
                    rowsName.append( ","+o.toString());
                    Object o1 = map.get(o);
                    if(StringUtils.isEmpty(o1)){
                        rowsValue.append(", ''");
                    }else{
                        rowsValue.append( ",'"+o1.toString()+"'");
                    }
                }
            }
            if("1".equals(datagovernancetype)){
                rowsName.append(",altertable_type");
                rowsValue.append( ",'delete'");
            }else{
                rowsName.append(",altertable_type");
                rowsValue.append( ",'update'");
            }

            rowsName.append(",altertable_time");

            Date date =new Date();
            SimpleDateFormat  sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = sdf.format(date);
            rowsValue.append(",'"+format);
            rowsValue.append("'");

            String substringRowsName = rowsName.substring(1);
            String substringRowsValue = rowsValue.substring(1);

            //INSERT INTO table_name (列1, 列2,...) VALUES (值1, 值2,....)

            String sql = "insert into "+" "+tablenameNew+" "+"("+" "+substringRowsName+" "+") values ("+" "+substringRowsValue+" "+")";
            int i = entityManager.createNativeQuery(sql).executeUpdate();

            JSONObject jsonObject =new JSONObject();
            jsonObject.put("status","true");

            return jsonObject;

        }
        catch (Exception e){
            JSONObject jsonObject =new JSONObject();
            jsonObject.put("status","false");

            return jsonObject;

        }

    }

删除

第一种
@Transactional
    @Modifying
    @Query(value = "delete  GSGUOXIN_PUSHED where id = :id", nativeQuery = true)
    void deleteGuoXinPush(@Param("id") String id);

第二种
 /**
     *
     * @param tablenameOld 表名
     * @param datagovernancetype 更新类型
     * @param condition 条件
     * @param split 更细字段分离出来的内容
     * @param jsonArray 前段返回值
     * @return
     */
    @Transactional
    @Modifying
    public int updatetablenameOld(String tablenameOld,String datagovernancetype,String condition,String[] split,JSONArray jsonArray) {

        int res =0;

        String sql = "";
        //1表示delete,0表示update
        if("1".equals(datagovernancetype)){

            //DELETE FROM Person WHERE LastName = 'Wilson'
            sql = "delete from "+" "+tablenameOld+" "+"where"+" "+condition;


            res = entityManager.createNativeQuery(sql).executeUpdate();

            return res;
        }else{

            //UPDATE Person SET FirstName = 'Fred' WHERE LastName = 'Wilson'
            sql = "update "+" "+tablenameOld+" "+"set";

            for (int i = 0; i < split.length; i++) {
                String splits = split[i];
                for (int j = 0; j < jsonArray.size(); j++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(j);
                    String key = jsonObject.getString("key");
                    if(key.equals(splits)){
                        sql = sql +" "+jsonObject.getString("key")+" "+"="+" '"+jsonObject.getString("value")+"' "+",";
                    }
                }
            }
            sql = sql.substring(0,sql.length()-1);
            sql = sql+"where"+" "+condition;
            res = entityManager.createNativeQuery(sql).executeUpdate();

            return res;
        }




    }

修改

第一种
@Transactional
    @Modifying
    @Query(value = "update  GSGUOXIN_PUSHED o set o.DJBH = :DJBH where o.id = :id", nativeQuery = true)
    void updateGuoXinPush(@Param("id") String id,@Param("DJBH") String DJBH);
第二种
/**
     *
     * @param tablenameOld 表名
     * @param datagovernancetype 更新类型
     * @param condition 条件
     * @param split 更细字段分离出来的内容
     * @param jsonArray 前段返回值
     * @return
     */
    @Transactional
    @Modifying
    public int updatetablenameOld(String tablenameOld,String datagovernancetype,String condition,String[] split,JSONArray jsonArray) {

        int res =0;

        String sql = "";
        //1表示delete,0表示update
        if("1".equals(datagovernancetype)){

            //DELETE FROM Person WHERE LastName = 'Wilson'
            sql = "delete from "+" "+tablenameOld+" "+"where"+" "+condition;


            res = entityManager.createNativeQuery(sql).executeUpdate();

            return res;
        }else{

            //UPDATE Person SET FirstName = 'Fred' WHERE LastName = 'Wilson'
            sql = "update "+" "+tablenameOld+" "+"set";

            for (int i = 0; i < split.length; i++) {
                String splits = split[i];
                for (int j = 0; j < jsonArray.size(); j++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(j);
                    String key = jsonObject.getString("key");
                    if(key.equals(splits)){
                        sql = sql +" "+jsonObject.getString("key")+" "+"="+" '"+jsonObject.getString("value")+"' "+",";
                    }
                }
            }
            sql = sql.substring(0,sql.length()-1);
            sql = sql+"where"+" "+condition;
            res = entityManager.createNativeQuery(sql).executeUpdate();

            return res;
        }




    }

查询

第一种
@Query(value = "select * from GSGUOXIN_PUSHED o where o.DJWCSj >= to_timestamp(:DJWCSj, 'YYYY-MM-DD')", nativeQuery = true)
    List<GuoXinPush> findYearOfAllGuoxin( @Param("DJWCSj") String DJWCSj);

第二种
 //查询是否有对应的表
    @Transactional
    @Modifying
    public JSONObject selectTablename(String tablenameOld , String tablenameNew) {
        JSONObject result = new JSONObject();

        try {
            String  sql = "select count(*) from user_tables where table_name =upper('"+tablenameNew+"')";
            javax.persistence.Query query = entityManager.createNativeQuery(sql);
            query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
            List<Map> rows = query.getResultList();
            String count = rows.get(0).get("COUNT(*)").toString();

            if("0".equals(count)){
                result.put("status","false");
                result.put("message","不存在对应表");
                return result;
            }else {
                JSONObject jsonObject = compareTableStructure(tablenameOld, tablenameNew);

//                if("true".equals(jsonObject.getString("status"))){
//
//                }
//                else {
//                    return jsonObject;
//                }
//                result.put("status","true");
//                result.put("message","null");
                return jsonObject;
            }


        }catch (Exception sqlex) {
            result.put("status","false");
            result.put("message","不存在对应表");
            return result;
        }
    }

差别和感受

其实我感觉后面一种的操作性更加的高,可以看看我的上一篇博客,可以去直接新建表,不是说第一种不行,只是我不知道方法,感觉越学越知道内容多感觉自己无知,那是真的无知,多学学吧。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
/* * Copyright (c) 2000 David Flanagan. All rights reserved. * This code is from the book Java Examples in a Nutshell, 2nd Edition. * It is provided AS-IS, WITHOUT ANY WARRANTY either expressed or implied. * You may study, use, and modify it for any non-commercial purpose. * You may distribute it non-commercially as long as you retain this notice. * For a commercial use license, or to purchase the book (recommended), * visit http://www.davidflanagan.com/javaexamples2. */ package com.hexiang.examples.servlet; import javax.servlet.*; import javax.servlet.http.*; import java.sql.*; import java.io.*; /** * This class demonstrates how JDBC can be used within a servlet. It uses * initialization parameters (which come from the web.xml configuration file) * to create a single JDBC database connection, which is shared by all clients * of the servlet. ***/ public class Query extends HttpServlet { private static final long serialVersionUID = -5616899811848789885L; Connection db; // This is the shared JDBC database connection public void init() throws ServletException { // Read initialization parameters from the web.xml file ServletConfig config = getServletConfig(); String driverClassName = config.getInitParameter("driverClassName"); String url = config.getInitParameter("url"); String username = config.getInitParameter("username"); String password = config.getInitParameter("password"); // Use those init params to establish a connection to the database // If anything goes wrong, log it, wrap the exception and re-throw it try { Class.forName(driverClassName); db = DriverManager.getConnection(url, username, password); } catch (Exception e) { log("Can't create DB connection", e); throw new ServletException("Query: can't initialize: " + e.getMessage(), e); } } /** Close the database connection when the servlet is unloaded */ public void destroy() { try { db.close(); } // Try to close the connection catch (SQLException e) {} // Ignore errors; at least we tried! } public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); // We're outputting HTML PrintWriter out = response.getWriter(); // Where to output it to // Output document header and a form for entering SQL queries // When the form is submitted, this servlet is reloaded out.println("<head><title>DB Query</title></head>\n" + "<body bgcolor=white><h1>DB Query</h1>\n" + "<form><b>Query: </b><input name='q'>" + "<input type=submit></form>"); // See if a query was specified in this request. String query = request.getParameter("q"); if (query != null) { // display the query text as a page heading out.println("<h1>" + query + "</h1>"); // Now try to execute the query and display the results in a table Statement statement = null; // An object to execute the query try { // Create a statement to use statement = db.createStatement(); // Use it to execute the specified query, and get result set ResultSet results = statement.executeQuery(query); // Ask for extra information about the results ResultSetMetaData metadata = results.getMetaData(); // How many columns are there in the results? int numcols = metadata.getColumnCount(); // Begin a table, and output a header row of column names out.println("<table border=2><tr>"); for(int i = 0; i < numcols; i++) out.print("<th>" + metadata.getColumnLabel(i+1) + "</th>"); out.println("</tr>"); // Now loop through the "rows" of the result set while(results.next()) { // For each row, display the the values for each column out.print("<tr>"); for(int i = 0; i < numcols; i++) out.print("<td>" + results.getObject(i+1) + "</td>"); out.println("</tr>"); } out.println("</table>"); // end the table } catch (SQLException e) { // If anything goes wrong (usually a SQL error) display the // error to the user so they can correct it. out.println("SQL Error: " + e.getMessage()); } finally { // Whatever happens, always close the Statement object try { statement.close(); } catch(Exception e) {} } } // Now, display the number of hits on this page by invoking the // Counter servlet and including its output in this page. // This is done with a RequestDispatcher object. RequestDispatcher dispatcher = request.getRequestDispatcher("/servlet/counter"); if (dispatcher != null) { out.println("<br>Page hits:"); // Add a request attribute that tells the servlet what to count. // Use the attribute name defined by the Counter servlet, and // use the name of this class as a unique counter name. request.setAttribute(Counter.ATTRIBUTE_NAME,Query.class.getName()); // Tell the dispatcher to invoke its servlet and include the output dispatcher.include(request, response); } // Finally, end the HTML output out.println("</body>"); } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

又是重名了

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值