JdbcUtil

轉自:https://github.com/ghyg525/util_java_jdbc

?JdbcUtil.java

import java.io.IOException;
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.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;/*** 簡單封裝數據庫工具類* 查詢返回結果有數組, List, Map* 其他類型語句都調用execute* @author YJ*/
public class JdbcUtil {/*** 查詢返回String二維數組* @param sql* @param args* @return*/public static String[][] queryForArray(String sql, Object... args) {Connection conn = null;PreparedStatement stmt = null;ResultSet rs = null;String[][] result = null;try {conn = getConnection();stmt = conn.prepareStatement(sql,ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);if (args != null) {for (int i = 0; i < args.length; i++) {stmt.setObject(i + 1, args[i]);}}rs = stmt.executeQuery();rs.last();int rows = rs.getRow();rs.beforeFirst();ResultSetMetaData rsmd = rs.getMetaData();int cols = rsmd.getColumnCount();result = new String[rows+1][cols];for (int i = 0; i < cols; i++) {result[0][i] = rsmd.getColumnName(i + 1);}int currentRow = 1;while (rs.next()) {for (int i = 0; i < cols; i++) {result[currentRow][i] = rs.getObject(i + 1).toString();}currentRow++;}} catch (SQLException e) {e.printStackTrace();} finally {try {if (rs != null)rs.close();if (stmt != null)stmt.close();if (conn != null)conn.close();} catch (SQLException e) {e.printStackTrace();}}return result;}/*** 查詢返回List類型* @param sql* @param args* @return 多條記錄的List集合*/public static List<Map<String, Object>> queryForList(String sql, Object... args) {Connection conn = null;PreparedStatement stmt = null;ResultSet rs = null;List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();try {conn = getConnection();stmt = conn.prepareStatement(sql);if (args != null) {for (int i = 0; i < args.length; i++) {stmt.setObject(i + 1, args[i]);}}rs = stmt.executeQuery();ResultSetMetaData rsmd = rs.getMetaData();int cols = rsmd.getColumnCount();String[] colNames = new String[cols];for (int i = 0; i < cols; i++) {colNames[i] = rsmd.getColumnName(i + 1);}while (rs.next()) {Map<String, Object> row = new LinkedHashMap<String, Object>();for (int i = 0; i < cols; i++) {row.put(colNames[i], rs.getObject(i + 1));}result.add(row);}} catch (SQLException e) {e.printStackTrace();} finally {try {if (rs != null)rs.close();if (stmt != null)stmt.close();if (conn != null)conn.close();} catch (SQLException e) {e.printStackTrace();}}return result;}/*** 查詢返回Map類型 當確定返回結果唯一時調用* @param sql* @param args* @return 一條記錄的Map*/public static Map<String, Object> queryForMap(String sql, Object... args) {List<Map<String, Object>> result = queryForList(sql, args);Map<String, Object> row = null;if (result.size() == 1) {row = result.get(0);return row;} else {return null;}}/*** 執行除查詢外(增加/刪除/修改)* @param sql* @param args* @return 是否執行成功*/public static boolean execute(String sql, Object... args) {Connection conn = null;PreparedStatement stmt = null;boolean result = true;try {conn = getConnection();stmt = conn.prepareStatement(sql);if (args != null) {for (int i = 0; i < args.length; i++) {stmt.setObject(i + 1, args[i]);}}stmt.executeUpdate();} catch (SQLException e) {e.printStackTrace();result = false;} finally {try {if (stmt != null)stmt.close();if (conn != null)conn.close();} catch (SQLException e) {e.printStackTrace();}}return result;}/*** 獲得數據庫連接* @return*/private static Connection getConnection() {Connection conn = null;try {Class.forName(getProperties().getProperty("driver"));conn = DriverManager.getConnection(getProperties().getProperty("url"),getProperties().getProperty("username"), getProperties().getProperty("password"));} catch (ClassNotFoundException e) {e.printStackTrace();} catch (SQLException e) {e.printStackTrace();}return conn;}/*** 讀取配置文件信息* @return*/private static Properties getProperties(){Properties properties = new Properties();try {properties.load(JdbcUtil.class.getResourceAsStream("/jdbc.properties"));} catch (IOException e) {e.printStackTrace();}return properties;}}

?

jdbc.properties

url=jdbc:mysql://localhost:3306/esweb
driver=com.mysql.jdbc.Driver
username=root
password=root

?

測試:

public class JdbcMysql {public static void main(String[] args) {String sql1 = "select * from screen_201808";String sql2 = "select * from screen_201808 where id = ?";System.out.println(JdbcUtil.queryForArray(sql1)[1][1]);System.out.println(JdbcUtil.queryForList(sql1));System.out.println(JdbcUtil.queryForMap(sql2,1));}
}

?

?參考文檔:

https://github.com/ghyg525/util_java_jdbc

https://www.shiyanlou.com/courses/110

轉載于:https://www.cnblogs.com/libin2015/p/9443395.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/388859.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/388859.shtml
英文地址,請注明出處:http://en.pswp.cn/news/388859.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

機器學習 綜合評價_PyCaret:機器學習綜合

機器學習 綜合評價Any Machine Learning project journey starts with loading the dataset and ends (continues ?!) with the finalization of the optimum model or ensemble of models for predictions on unseen data and production deployment.任何機器學習項目的旅程都…

silverlight 3D 游戲開發

http://www.postvision.net/SilverMotion/DemoTech.aspx silverlight 3D 游戲開發 時間:2010-10-22 06:33來源:開心銀光 作者:黎東海 點擊: 562次意外發現一個silverlight的實時3D渲染引擎。性能比開源那些強很多。 而且支持直接加載maya,3Dmax等主流3D模型文件。 附件附上它的…

redis終端簡單命令

keys * 獲取所有鍵lRange hongbao:44 0 -1獲取該鍵的所有值del hongbao:44 刪除該鍵的所有值 hgetAll user:44 獲取該鍵的所有隊列hget hongbao:44 8 獲取該隊列用戶為8的值hset hongbao:44 7 asdf設置該隊列用戶為7的值hdel user:44 8 刪除該隊列用戶為8的值 flushall 清空red…

python中ix用法_Python中使用ix的數據幀子集

您可以使用X[var2].iloc[[0,1]]&#xff1a;In [280]: X[var2].iloc[[0,1]]Out[280]:0 NaN4 9Name: var2, dtype: float64由于X[var2]是X的視圖&#xff0c;因此X[var2].iloc[[0,1]]對兩者都是安全的訪問和分配。但是如果你使用這種“鏈式索引”要小心模式(例如這里使用的index…

LintCode 16. 帶重復元素的排列

寫在前面&#xff1a;這題和全排列不含重復元素的那題幾乎一樣&#xff0c;我比較垃圾&#xff0c;就用HashSet去掉了重復的元素但是看了九章算法的答案也沒看懂&#xff0c;他寫的很有感覺。 用了hash&#xff0c;本來想著怎么寫hashcode()和equal()方法的&#xff0c;哪知道都…

皮爾遜相關系數 相似系數_皮爾遜相關系數

皮爾遜相關系數 相似系數數據科學和機器學習統計 (STATISTICS FOR DATA SCIENCE AND MACHINE LEARNING) In the last post, we analyzed the relationship between categorical variables and categorical and continuous variables. In this case, we will analyze the relati…

【洛谷】P1641 [SCOI2010]生成字符串(思維+組合+逆元)

題目 傳送門&#xff1a;QWQ 分析 不想畫圖。 https://www.luogu.org/problemnew/solution/P1641 好神仙的題啊。 代碼 1 // luogu-judger-enable-o22 #include <bits/stdc.h>3 using namespace std;4 typedef long long ll;5 const int maxn15000000;6 const ll MOD2010…

Kubernetes持續交付-Jenkins X的Helm部署

Jenkins X 是一個集成化的 CI / CD 平臺&#xff0c;可用于 部署在Kubernetes集群或云計算中心。支持在云計算環境下簡單地開發和部署應用。本項目是在Kubernetes上的安裝支持工具集。 本工具集中包含&#xff1a; Jenkins - 定制好的流水線和運行環境&#xff0c;完全整合CI/C…

中國石油大學(華東)暑期集訓--二進制(BZOJ5294)【線段樹】

問題 C: 二進制 時間限制: 1 Sec 內存限制: 128 MB提交: 8 解決: 2[提交] [狀態] [討論版] [命題人:]題目描述 pupil發現對于一個十進制數&#xff0c;無論怎么將其的數字重新排列&#xff0c;均不影響其是不是3的倍數。他想研究對于二進制&#xff0c;是否也有類似的性質。于…

2018年10個最佳項目管理工具及鏈接

要在任何業務中取得成功&#xff0c;對項目進行適當的管理非常重要。 項目管理是一系列活動&#xff0c;包括計劃&#xff0c;執行&#xff0c;控制和完成項目。項目管理工具有助于簡化此過程。這里是Best 10項目管理工具及其功能和下載鏈接的精選列表。1&#xff09;AsanaAsan…

Java 8 新特性之Stream API

1. 概述 1.1 簡介 Java 8 中有兩大最為重要的改革&#xff0c;第一個是 Lambda 表達式&#xff0c;另外一個則是 Stream API&#xff08;java.util.stream.*&#xff09;。 Stream 是 Java 8 中處理集合的關鍵抽象概念&#xff0c;它可以指定你希望對集合進行的操作&#xff0c…

[Python設計模式] 第17章 程序中的翻譯官——適配器模式

github地址:https://github.com/cheesezh/python_design_patterns 適配器模式 適配器模式&#xff0c;將一個類的接口轉換成客戶希望的另外一個接口。Adapter模式使得原本由于接口不兼容而不能一起工作的那些類可以一起工作[DP]。 當系統的數據和行為都正確&#xff0c;但是接口…

Ubuntu中NS2安裝詳細教程

前言&#xff1a; NS2是指 Network Simulator version 2&#xff0c;NS&#xff08;Network Simulator&#xff09; 是一種針對網絡技術的源代碼公開的、免費的軟件模擬平臺&#xff0c;研究人員使用它可以很容易的進行網絡技術的開發&#xff0c;而且發展到今天&#xff0c;它…

es6核心特性圖

轉載于:https://juejin.im/post/5c19e188e51d452db4753925

帶你利用一句話完成轉場動畫

這篇文章主要給大家介紹了關于iOS如何利用一句話完成轉場動畫的相關資料&#xff0c;文中通過示例代碼介紹的非常詳細&#xff0c;對大家的學習或者工作具有一定的參考學習價值&#xff0c;需要的朋友們下面來一起學習學習吧前言本文介紹SS_AnimationTransition 的使用方法,利用…

14.vue路由腳手架

一.vue路由&#xff1a;https://router.vuejs.org/zh/ 1、定義 let router new VueRouter({mode:"history/hash",base:"基本路徑" 加一些前綴 必須在history模式下有效linkActiveClass:"active", 范圍選擇linkExactActiveClass:"exact&qu…

工程師、產品經理、數據工程師是如何一起工作的?

做為一名工程師&#xff0c;免不了與產品經理打交道&#xff0c;如果公司大一些&#xff0c;數據量多一些&#xff0c;還會有數據工程師這個角色。今天會和你主要聊一聊在工作中&#xff0c;產品經理和數據工程師在哪些方面對我們工程師的幫助最大&#xff0c;以及我從他們身上…

linux-buff/cache過大導致內存不足-程序異常

2019獨角獸企業重金招聘Python工程師標準>>> 問題描述 Linux內存使用量超過閾值&#xff0c;使得Java應用程序無可用內存&#xff0c;最終導致程序崩潰。即使在程序沒有掛掉時把程序停掉&#xff0c;系統內存也不會被釋放。 找原因的過程 這個問題已經困擾我好幾個月…

Android 適配(一)

一、Android適配基礎參數1.常見分辨率&#xff08;px&#xff09;oppx 2340x1080oppR15 2280x1080oppor11sp 2160*10801080*1920 (主流屏幕16&#xff1a;9)1080*216018:9 手機主流分辨率&#xff1a; 1080*2160高端 16:9 手機主流分辨率&#xff1a; 1080P (1080*1920) 或 2K …

Source Insight 創建工程(linux-2.6.22.6內核源碼)

1. 軟件設置 安裝完Source Insight&#xff0c;需要對其進行設置添加對“.S”匯編文件的支持&#xff1a; 2. 新建linux-2.6.22.6工程 1&#xff09;選擇工程存放的路徑&#xff1a; 2&#xff09;下載linux-2.6.22.6內核源碼&#xff0c;并解壓。在Source Insight中 指定源碼的…