Get the App
SLTechnology News&Howtos  ›  Development  › 

How to connect java to mysql underlying encapsulation

Shulou Source: shulou.com Published: 2022-06-02 02:30:18 11月27日 Update

This article mainly introduces how to connect java to the underlying package of mysql, which is very detailed and has certain reference value. Interested friends must finish reading it!

The details are as follows

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 * @ 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 () > zero 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 ritual 1)

Tags: Data database encapsulation bottom layer content articles queries success value interests parameters fields guys partners more knowledge results industry information information channels Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Tech Info Docker NVidia Linux Microsoft