Get the App
SLTechnology News&Howtos  ›  Database  › 

Example Analysis of the underlying Encapsulation of java connection mysql

Shulou Source: shulou.com Published: 2022-05-31 20:34:19 09月12日 Update

Editor to share with you the java connection mysql underlying encapsulation example analysis, I believe that most people do not know much about it, so share this article for your reference, I hope you will learn a lot after reading this article, let's go to know it!

Connect to the database

Package com.dao.db;import java.sql.Connection;import java.sql.SQLException;/** * database connection layer MYSQL * @ author Administrator * * / public class DBConnection {/ * connect to the database * @ return * / public static Connection getDBConnection () {/ / 1. Registered driver try {Class.forName ("com.mysql.jdbc.Driver");} catch (ClassNotFoundException e) {/ / TODO Auto-generated catch block e.printStackTrace ();} / / get the connection to the database try {Connection conn = java.sql.DriverManager.getConnection ("jdbc:mysql://localhost/mysql?useUnicode=true&characterEncoding=utf-8", "root", "root"); return conn;} catch (SQLException E1) {e1.printStackTrace () } return null;}}

Data layer encapsulation

Package com.dao.db;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.ResultSetMetaData;import java.sql.SQLException;import java.sql.Types;import java.util.ArrayList;import java.util.HashMap;/** * MYSQL database underlying encapsulation * @ author Administrator * * / public class DBManager {private PreparedStatement pstmt; private Connection conn; private ResultSet rs / * Open database * / public DBManager () {conn = DBConnection.getDBConnection ();} / * perform modify and add operation * @ param coulmn * @ param type * @ param sql * @ return * @ throws SQLException * / public boolean updateOrAdd (String [] coulmn, int [] type, String sql) throws SQLException {if (! setPstmtParam (coulmn, type, sql) return false; boolean flag = pstmt.executeUpdate () > 0?true:false CloseDB (); return flag;} / * get query result set * @ param coulmn * @ param type * @ param sql * @ throws SQLException * / public DataTable getResultData (String [] coulmn, int [] type, String sql) throws SQLException {DataTable dt = new DataTable (); ArrayListlist = new ArrayList (); if (! setPstmtParam (coulmn, type, sql) return null; rs = pstmt.executeQuery (); ResultSetMetaData rsmd = rs.getMetaData () / / take the column name of the database int numberOfColumns = rsmd.getColumnCount (); while (rs.next ()) {HashMap rsTree = new HashMap (); for (int rud1terr)

Tags: Data database encapsulation underlying article example analysis content query success not much parameters most fields more knowledge results industry information information channels Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Apple MariaDB macOS Huawei Shulou Technology