briup_jdbc self-built tools Redux

Summary: The build tools, the difficulty lies in the query, the required functionality is either oracle or mysql can connect and provide the required entity class, all queries can be encapsulated into an entity class to go

Difficulties encountered when a connection is read from the drive like url prpperties.txt file, how it is loaded at this time can come class loader to load the appropriate class file currently .class.classloader (). GetResourceAsStream (File address: src attention this time not from the beginning to write s path from the package name)

 

 

 

The second difficulty: the time when building a query, oracle database using a query to the column name is capitalized, it needs to be converted to lowercase

      The number oracle java type will resolve to the BigDecimal, it needs to be converted, and then converted into int 

 

Code:

 

package com.briup.jdbc;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;

oracle.net.aso.l Import; 

public class JDBCUtils3 { 
    // get links 
    public static Connection the getConnection (STR String, String filePath) { 
        IF ( "MySQL" .equals (STR)) { 
            the try { 

                the Properties Properties new new = the Properties () ; 
                the FileInputStream FIS = null; 
                the try { 
                    FIS new new = the FileInputStream (new new file (filePath)); 
                } the catch (a FileNotFoundException E2) { 
                    e2.printStackTrace (); 
                } 
          // input stream may alternatively custom class loader (need to document placed under the package) // InputStream in = // JdbcUtils2.class.getClassLoader () the getResourceAsStream ( "COM / briup / JDBC / properties.txt").; try { properties.load(fis); } catch (IOException e1) { e1.printStackTrace(); } String driver = (String) properties.get("driver"); String url = (String) properties.get("url"); String username = (String) properties.get("username"); String password = (String) properties.get("password"); Class.forName(driver); try { Connection conn = DriverManager.getConnection(url, username, password); // System.out.println("连接到mysql数据库" + conn); return conn; } catch (SQLException e) { e.printStackTrace(); } } catch (ClassNotFoundException e) { e.printStackTrace(); } } if ("oracle".equals(str)) { Properties properties = new Properties(); FileInputStream fis = null; try { fis = new FileInputStream(new File(filePath)); } catch (FileNotFoundException e2) { e2.printStackTrace(); } try { properties.load(fis); } catch (IOException e1) { e1.printStackTrace(); } String driver = (String) properties.get("driver"); String url = (String) properties.get("url"); String username = (String) properties.get("username"); String password = (String) properties.get("password"); try { Class.forName(driver); try { Connection conn = DriverManager.getConnection(url, username, password); System.out.println("连接到orcle数据库"); return conn; } catch (SQLException e) { e.printStackTrace(); } } catch (ClassNotFoundException e) { e.printStackTrace (); } } return null; } // general inquiry method public static
< T > List < T > of query2 (Connection Conn, SS String, String SQL, Object ... args) { List < T > List = null; the try { // Get the object prepareStatement the PreparedStatement prepareStatement = conn.prepareStatement (sql); // parameter (placeholders) passed in the entire sql statement good supplement for (int 0 = I; I < args .length; I ++) { // Note: It should be + 1'd prepareStatement.setObject (I +. 1, args [I]); } // result sets the ResultSet the resultSet = prepareStatement.executeQuery (); // get the results here prepared all set inside the column names List <String > Labels new new = the ArrayList < String > (); // get all set (metadata) column name in the database the ResultSetMetaData ResultSet.getMetaData the metaData = (); for (int I = 0 ; I < the metaData .getColumnCount (); I ++) { // here again to add 1, 1 counted from labels.add (metaData.getColumnLabel (I +. 1)); } // Create a map, the query field name, and its value is stored into the map, in order to remove // key: column name, value: field the value of the HashMap <String, Object > Map new new = the HashMap < String , Object > (); // Create a list, storing data List new new = the ArrayList < T > (); // S is the column name while (resultSet.next ()) { map.clear (); for (String S: Labels) { map.put (S, ResultSet.getObject (S)); } // If the map is not empty, traversing the map, its value will be stored into the entity class go with if (!map.isEmpty()) { Set<Entry<String, Object>> entrySet = map.entrySet(); for (Entry<String, Object> entry : entrySet) { System.out.print(entry.getKey()+":"+entry.getValue()+" "); if(entry.getKey().equals(ss)) { System.out.println(); } } } } } catch (SQLException e) { e.printStackTrace(); } return list; } // general inquiry method public static < T > List < T > Query (Class < T > < T > List = null; the try { // Get the object prepareStatement the PreparedStatement prepareStatement = conn.prepareStatement (SQL); // pass through incoming parameters (placeholders), the entire supplementary good sql statement for (int I = 0; I < args .length; I ++) { // Note: It should be + 1'd prepareStatement.setObject (I +. 1, args [I ]); } // set the result obtained tClass, Connection conn, String sql, Object... args) { List the resultSet the resultSet = prepareStatement.executeQuery (); // get the result sets prepared here inside All column names List <String > Labels new new = the ArrayList < String > (); // Get the full set of (metadata) column name in the database the ResultSetMetaData ResultSet.getMetaData The metaData = (); for (int I = 0; I < The metaData .getColumnCount (); I ++) { // Here again to add 1, from 1 start counting labels.add (metaData.getColumnLabel (I + 1)); } // Create a map, the query field name, and its value is stored into the map, in order to remove // key: column name, value: value of the field The HashMap <String, Object (); // S is a column name> Map new new = the HashMap < String , Object > (); // Create a list, storing data List new new = the ArrayList < T > // create an instance, use reflected here the while (ResultSet.next ()) { map.clear (); for (String S: Labels) { map.put (S, ResultSet.getObject (S)); } // If the map is not empty, traversing the map, the its value is stored to the entity class IF {(map.isEmpty ()!) the try { T = tClass.newInstance the newInstance (); the Set < the Entry <String, Object > > EnumMap.entrySet the entrySet = (); for (the Entry < String , Object > entry: the entrySet) { String name = entry.getKey(); Object value = entry.getValue(); if(value instanceof BigDecimal) { value=((BigDecimal) value).intValue(); } try { // 获取属性,给属性赋值 Field field = tClass.getDeclaredField(name.toLowerCase()); field.setAccessible(true); field.set(newInstance, value); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } } list.add(newInstance); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } } } catch (SQLException e) { e.printStackTrace(); } return list; } // 删除数据 public static void delete(Connection conn, String sql) { try { Statement statement = conn.createStatement(); try { statement.execute(sql); System.out.println("删除数据成功!"); } catch (Exception e) { System.err.println("出现问题了" + e.getMessage()); e.printStackTrace(); } The catch} (SQLException E) { e.printStackTrace (); } } // modify a data public static void the Update (Connection Conn, String SQL) { the try { Statement statement = conn.createStatement(); try { Statement.execute (SQL); System.out.println ( "Modify Data success "); } the catch (Exception E) { System.err.println (" a problem "+ e.getMessage ()); e.printStackTrace (); } } the catch (SQLException E) { e.printStackTrace (); } } // add a data public static void the Add (Connection Conn, String SQL) { the try { the Statement Statement conn.createStatement = (); the try { Statement.execute ( SQL); System.out.println ( "insert data is successfully!"); } the catch (Exception E) { System.err.println("出现问题了" + e.getMessage()); e.printStackTrace(); } } catch (SQLException e) { e.printStackTrace(); } } // 关闭连接 public static void close(Statement st, ResultSet rs, Connection conn) { if (st != null) { try { st.close(); } catch (SQLException e) { e.printStackTrace(); } } if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } }

 

Guess you like

Origin www.cnblogs.com/yue-170305/p/11489893.html