java與mysql的交互_java與數據庫交互常用到的一些方法

下面我整理了一下java中常用的幾個與數據庫交互的常用方法,僅供參考:

1.執行SQL(dao層的實現類中)

(1)SQL查詢:

//import org.hibernate.Query;

//import org.hibernate.Session;

/*** 通過名稱查找id

*@parampsname

*@returnid*/@OverridepublicString findEnterpriseId(String psname) {

String id= "";//查找信息的sql

String sql = "select id from t_enterprise where psname = '"+psname+"'";//創建Query對象接收通過createSqlQuery()方法解析sql語句得到的結果//方式一:

Query query = this.createSqlQuery(sql);//方式二://Session session = getSession();//Query query = session.createSQLQuery(sql);

//存儲過程鍵值對應

//sqlQuery.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);

List list =query.list();for (int i = 0; i < list.size(); i++) {

Object obj= list.get(0);if (obj!=null) {

id=obj.toString();

}

}returnid;

}

(2)SQL修改或刪除

@Overridepublic void updateWeather(ActuallyWeather actuallyWeather) throwsException {

String sql= "update t_actually_weather set forecast_time = '"+actuallyWeather.getForecastTime()+"',"

+ "max_temperature = '"+actuallyWeather.getMaxTemperature()+"',"

+ "min_temperature = '"+actuallyWeather.getMinTemperature()+"',"

+ "place_name = '"+actuallyWeather.getPlaceName()+"',"

+ "pub_time = '"+actuallyWeather.getPubTime()+"',"

+ "weather_status = '"+actuallyWeather.getWeatherStatus()+"',"

+ "wind_power = '"+actuallyWeather.getWindPower()+"'"

+ " where id = '"+actuallyWeather.getId()+"'";this.getSession().clear();this.createSqlQuery(sql).executeUpdate();

}

2.執行HQL(dao層的實現類中)

(1)返回Page

1)//action中page屬性

private Page page = new Page(Constants.DEFAULT_PAGE_SIZE, true);2)

page參數在(action)中只需要設置如下:

page.setPageNo(this.getPageNo());

page.setPageSize(this.getPageSize());3)/*** 查詢

*@parampage

*@paramfilterMap*/@SuppressWarnings("rawtypes")

@Overridepublic Page findAllEnterprise(Pagepage,Map filterMap){

String hql= " from UnifiedEnterInfo s where 1=1 ";//污染源名稱

String psname = (String) filterMap.get("psname");if(StringUtils.isNotEmpty(psname)) {

String[] str= psname.split(" ");

String reg= "";for (int i = 0; i < str.length; i++) {

reg=str[i];if (!"".equals(reg)) {

hql= hql+" and psname like '%"+reg+"%'";

}

}//hql = hql+" and psname like '%"+psname.trim()+"%'";

}//系統來源

String systemSource = (String) filterMap.get("systemSource");if(StringUtils.isNotEmpty(systemSource)) {

hql= hql+" and systemSource = "+systemSource;

}//所屬區域

String regionCode = (String) filterMap.get("regionCode");if(StringUtils.isNotEmpty(regionCode)) {if(!"110100".equals(regionCode))

hql= hql+" and regionCode like '"+regionCode+"%'";

}//法人編碼

String corporationCode = (String) filterMap.get("corporationCode");if(StringUtils.isNotEmpty(corporationCode)) {

hql= hql+" and corporationCode like '%"+corporationCode.trim()+"%'";

}//法人名稱

String corporationName = (String) filterMap.get("corporationName");if(StringUtils.isNotEmpty(corporationName)) {

hql= hql+" and corporationName like '%"+corporationName.trim()+"%'";

}//地址

String addr = (String) filterMap.get("addr");if(StringUtils.isNotEmpty(addr)) {

hql= hql+" and addr like '%"+addr.trim()+"%'";

}//是否統一

String ifUinfied =(String)filterMap.get("ifUinfied");if("1".equals(ifUinfied)) {

hql= hql+" and mainOrChild=0";

}else if("2".equals(ifUinfied)){

hql= hql+" and mainOrChild!=0";

}

hql= hql+" order by ltrim(rtrim(psname)) asc";return this.find(page,hql);

}

(2)返回唯一值:

/*** 查詢獲取最大的統一污染源編碼*/@OverridepublicString findMaxUniqueCode(){

String hql= "select max(uniqueCode) from UnifiedEnterInfo ";return (String)this.findUnique(hql);

}

(3)返回List:

@Overridepublic ListgetUnifiedEnterInfosList(Map filterMap) {

String hql= " from UnifiedEnterInfo s where 1=1 ";

String psname= (String) filterMap.get("psname");if(StringUtils.isNotEmpty(psname)) {

hql= hql+" and psname like '%"+psname.trim()+"%'";

}

String corporationCode= (String) filterMap.get("corporationCode");if(StringUtils.isNotEmpty(corporationCode)) {

hql= hql+" and corporationCode like '%"+corporationCode.trim()+"%'";

}

String corporationName= (String) filterMap.get("corporationName");if(StringUtils.isNotEmpty(corporationName)) {

hql= hql+" and corporationName like '%"+corporationName.trim()+"%'";

}

String addr= (String) filterMap.get("addr");if(StringUtils.isNotEmpty(addr)) {

hql= hql+" and addr like '%"+addr.trim()+"%'";

}

hql= hql+" order by psname asc";return this.find(hql);

}

3.執行存儲過程(dao層的實現類中)

注意:如果查詢執行的時候數據庫返回”該語句沒有返回結果集。“這樣的錯誤,存儲過程中少了一句代碼:SET NOCOUNT ON

dfcaf7d20075e1fc4ee3f81761cb517a.png

(1)查詢:

publicList findPsList(String psCode) {

Long psCode1;//創建session對象

Session session = this.getSession();//創建事務的對象

Transaction trans =session.beginTransaction();//調用存儲過程

SQLQuery sqlQuery = session.createSQLQuery("{Call Proc_ZL_PSFlowRecharge(?)}");if ("".equals(psCode)||psCode==null) {

psCode1= (long) -1;

}else{

psCode1=Long.parseLong(psCode);

}//為存儲過程設置輸入參數

sqlQuery.setLong(0,psCode1 == null ? 0: psCode1);

//存儲過程鍵值對應

//sqlQuery.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);//提交事務

trans.commit();//獲取存儲過程的運行結果(得到的結果是Object類型的數組集合)存入list集合

List list =sqlQuery.list();returnlist;

}

(2)修改:

public String savePSGross(Mapmap) {

Date date= null;

SimpleDateFormat sf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

Long psCode1;//企業編碼

String psCode =(String) map.get("psCode");//污染因子編碼

String monitorItemCode =(String) map.get("monitorItemCode");//充值時間

String time = (String) map.get("time");//充值量

String acpNumber =(String) map.get("acpNumber");//充值類型

String rechargeType =(String) map.get("rechargeType");//創建session對象

Session session = this.getSession();//創建事務的對象

Transaction trans =session.beginTransaction();//調用存儲過程

SQLQuery query = session.createSQLQuery("{Call Proc_ZL_SavePSGrossInfo(?,?,?,?,?)}");if ("".equals(psCode)||psCode==null) {

psCode1= (long) -1;

}else{

psCode1=Long.parseLong(psCode);

}if(StringUtils.isNotEmpty(time)) {try{

date=sf.parse(time);

}catch(ParseException e) {

e.printStackTrace();

}

}//為存儲過程設置輸入參數

query.setLong(0,psCode1 == null ? 0: psCode1);

query.setString(1,monitorItemCode == null ? "": monitorItemCode);

query.setString(2,time == null ? "": time);

query.setBigDecimal(3,acpNumber == null ? new BigDecimal("0") : newBigDecimal(acpNumber));

query.setString(4,rechargeType == null ? "": rechargeType);

query.executeUpdate();return "success";

}

(3)用JDBC方式連接數據庫執行存儲過程:

工具類:

package com.jointsky.jointframe.ui.project.util;

import java.io.BufferedInputStream;

import java.io.FileInputStream;

import java.io.InputStream;

import java.sql.Connection;

import java.sql.DriverManager;

import java.util.Properties;

import com.jointsky.jointframe.system.config.service.JointFrameConfigManager;/**

*

*

Description:JDBC連接工具類

*

* @author liuf

* @date 2017-6-26

* @version 1.0*/

public classJdbcUtil {public staticConnection getConn() {String driverName= "com.microsoft.sqlserver.jdbc.SQLServerDriver";

String dbURL= "jdbc:sqlserver://localhost:1433;SelectMethod=cursor;DatabaseName=數據庫名";

String userName = "sa";

String userPwd= "123.com";Connection dbConn= null;try{

Class.forName(driverName);

dbConn=DriverManager.getConnection(dbURL, userName, userPwd);

System.out.println("連接數據庫成功");

}catch(Exception e) {

e.printStackTrace();

System.out.print("連接失敗");

}returndbConn;

}

}

調用方式:

@Overridepublic List getAllMonitorDatas(MapfilterMap)throwsException {

List list = new ArrayList();try{

Connection dbConn=JdbcUtil.getConn();

CallableStatement statement= dbConn.prepareCall("SET NOCOUNT ON exec dbo.ProcGetMonitorDatas ?,?,?,?,?,?,?,?");//開始時間

Date beginTime = (Date) filterMap.get("beginTime");//結束時間

Date endTime = (Date) filterMap.get("endTime");//編碼

String monitorPointCode = (String) filterMap.get("monitorPointCode");//編碼

String pollutantCode = (String)filterMap.get("pollutantCode");//編碼

String psCode = (String)filterMap.get("psCode");//類型

Integer outputType = (Integer)filterMap.get("outputType");//類型

Integer alarmType = (Integer) filterMap.get("alarmType");//類型細分

Integer alarmTypeDetails = (Integer) filterMap.get("alarmTypeDetails");if (endTime == null) {

endTime= newDate();

}//為存儲過程設置輸入參數

statement.setDate(1,new java.sql.Date(beginTime == null ? null: beginTime.getTime()));

statement.setDate(2,new java.sql.Date(endTime == null ? null: endTime.getTime()));

statement.setString(3,(String) (monitorPointCode == null ? "": monitorPointCode));

statement.setString(4,(String) (pollutantCode == null ? "": pollutantCode));

statement.setString(5,(String) (psCode == null ? "": psCode));

statement.setInt(6,outputType == null ? -1: outputType);

statement.setInt(7,alarmType == null ? -1: alarmType);

statement.setInt(8,alarmTypeDetails == null ? -1: alarmTypeDetails);

ResultSet rs=statement.executeQuery();while(rs.next()) {

MonitorData c= newMonitorData();//String id = rs.getString("id");//String monitorPointName = rs.getString("jkkljj");

c.setPsName(rs.getString("psName"));

c.setMonitorPointName(rs.getString("monitorPointName"));

c.setPollutantName(rs.getString("pollutantName"));

c.setMonitorTime(rs.getDate("monitorTime"));

c.setMonitorTimeCn(StringUtils.isEmpty(rs.getString("monitorTime")) ? "" : rs.getString("monitorTime").substring(0, 13) + "時");

c.setMonitorValueType(rs.getString("monitorValueType"));

c.setMonitorValue(rs.getString("monitorValue"));

c.setOutputType(Integer.parseInt(rs.getString("outputType")));

list.add(c);

}

statement.close();

}catch(Exception e1) {

e1.printStackTrace();

}returnlist;

}

4.用Criteria執行查詢:

public Page find(Pagepage,

MapfilterMap) {

Criteria criteria= this.createCriteria();try{if (filterMap.size() > 0) {

String name= filterMap.get("fullName");if(StringUtils.isNotEmpty(name)) {

criteria.add(Restrictions.like("fullName", name,

MatchMode.ANYWHERE));

}

String unit= filterMap.get("unit");if(StringUtils.isNotEmpty(unit)) {

criteria.add(Restrictions.like("unit", unit,

MatchMode.ANYWHERE));

}

criteria.addOrder(Order.asc("fullName"));

}

Page pages = this.findByCriteria(page, criteria);returnpages;

}catch(Exception e) {

e.printStackTrace();

}return null;

}

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

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

相關文章

xbmc電腦版本和手機版本學習教程

XBMC改名為Kodi了&#xff0c;IOS系統&#xff0c;Cydia源地址也同樣發生了變化&#xff0c;新的源是&#xff1a;http://mirrors.kodi.tv/apt/ios/先了解一下幾點知識&#xff1a; 教程中的各項操作&#xff0c;默認起始點都是“主界面”或“各分類菜單&#xff08;視頻、音樂…

線程管理(七)守護線程的創建和運行

聲明&#xff1a;本文是《 Java 7 Concurrency Cookbook 》的第一章&#xff0c; 作者&#xff1a; Javier Fernndez Gonzlez 譯者&#xff1a;鄭玉婷 校對&#xff1a;方騰飛 守護線程的創建和運行 Java有一種特別的線程叫做守護線程。這種線程的優先級非常低&#xff0c;通常…

vue2中的keep-alive使用總結及注意事項

問題總結;最近在寫vue移動端的項目的時候,當我切換菜單,再切換換回去的時候,發現頁面出現閃動的效果,其原因是因為切換回去之后,頁面重新渲染了;為了解決這一問題:查閱資料,只需要在 入口文件 App.vue 的router-view外層包裹一個keep-active標簽,表示該組件被保存在內存中,不需…

grove 套件_如何通過使用Andy Grove的High Leverage Activities加快發展?

grove 套件by Guido Schmitz由Guido Schmitz 如何通過使用Andy Grove的High Leverage Activities加快發展&#xff1f; (How to speed up your development by using Andy Grove’s High Leverage Activities ?) Youre constantly building on new features, fixing new bugs…

ajax php 觀察者模式,JavaScript觀察者模式定義和dom事件實例詳解

觀察者模式(發布-訂閱模式)&#xff1a;其定義對象間一種一對多的依賴關系&#xff0c;當一個對象的狀態發生改變時&#xff0c;所有依賴于它的對象都將得到通知。在JavaScript中&#xff0c;一般使用事件模型來替代傳統的觀察者模式。好處&#xff1a;(1)可廣泛應用于異步編程…

python中代碼段的標志是什么車_請問這段Python代碼是什么意思?

ord(p) - ord(a)這個意思是以 a 為序號0&#xff0c;計算字符p的序號。在ASCII字符集中&#xff0c;小寫字母a-z是連續排列的&#xff0c;因此如果a是0的話&#xff0c;那么b就是1&#xff0c;c就是2……以此類推。ord(p) - ord(a) 3前面一段我們解釋過了&#xff0c;那么這一…

servlet和jsp頁面過濾器Filter的作用及配置

剛剛有個朋友問我&#xff0c;Servlet的過濾器有什么作用&#xff1f; 現在發個帖子說明一下&#xff0c; 過濾器是一個對象&#xff0c;可以傳輸請求或修改響應。它可以在請求到達Servlet/JSP之前對其進行預處理&#xff0c;而且能夠在響應離開Servlet /JSP之后對其…

tar命令速查

tar -c: 建立壓縮檔案-x&#xff1a;解壓-t&#xff1a;查看內容-r&#xff1a;向壓縮歸檔文件末尾追加文件-u&#xff1a;更新原壓縮包中的文件 這五個是獨立的命令&#xff0c;壓縮解壓都要用到其中一個&#xff0c;可以和別的命令連用但只能用其中一個。下面的參數是根據需要…

附005.Docker Compose文件詳解

一 Docker Compose文件簡介 compose文件使用yml格式&#xff0c;主要分為了四個區域&#xff1a;version&#xff1a;用于指定當前docker-compose.yml語法遵循哪個版本services&#xff1a;服務&#xff0c;在它下面可以定義應用需要的一些服務&#xff0c;每個服務都有自己的名…

如何使用TensorFlow構建簡單的圖像識別系統(第2部分)

by Wolfgang Beyer沃爾夫岡拜爾(Wolfgang Beyer) 如何使用TensorFlow構建簡單的圖像識別系統(第2部分) (How to Build a Simple Image Recognition System with TensorFlow (Part 2)) This is the second part of my introduction to building an image recognition system wi…

網站 服務器 用sqlite,sqlite服務器數據庫

sqlite服務器數據庫 內容精選換一換簡要介紹SQLite是一款輕量級的關系型數據庫&#xff0c;它的運算速度非常快&#xff0c;占用資源很少&#xff0c;不僅支持標準的SQL語法&#xff0c;還遵循了數據庫的ACID事務。編寫語言&#xff1a;C一句話概述&#xff1a;輕量級的關系型數…

type-c接口圖片_TypeC接口除了充電還能干嗎?這些功能都不知道,簡直是在浪費...

Type C手機接口相信每個使用智能手機的朋友都很熟悉&#xff0c;目前已經廣泛使用在智能手機領域&#xff0c;并且得到用戶一致好評。但是對于Type C接口真正的用處很少有人知道&#xff0c;大部分用戶只了解正反面都可充電&#xff0c;其他方面一概不知&#xff0c;對于這一點…

Zookeeper的api的簡單使用(轉載)

轉載自: http://www.cnblogs.com/sunddenly/p/4031881.html 1.API 2.API 示例 ZooKeeper中的組成員關系 理解ZooKeeper的一種方法就是將其看作一個具有高可用性的文件系統。但這個文件系統中沒有文件和目錄&#xff0c;而是統一使用“節點”(node)的概念&#xff0c;稱為znode…

必須使用301重定向的運用場景

必須使用301重定向的運用場景

1.1好素數

題目 題意&#xff1a;一個好素數的定義是&#xff0c;他是一個素數&#xff0c;然后他的左右兩邊10區間內存在素數&#xff0c;那么他就是好素數&#xff0c;現在讓你輸入一個數字&#xff0c;這個數字以內的好素數的數量。 解題方法&#xff1a;先把每一個數字是不是素數判斷…

jquery.vue.js_一個Vue.js簡介,面向只了解jQuery的人

jquery.vue.jsby Matt Rothenberg馬特羅森伯格(Matt Rothenberg) 一個Vue.js簡介&#xff0c;面向只了解jQuery的人 (A Vue.js introduction for people who know just enough jQuery to get by) I’ve had a love-hate relationship with JavaScript for years.我與JavaScrip…

python 矩陣獲取行數_4個最佳項目創意的代碼片段和示例,旨在為Python和機器學習構建出色的簡歷!...

點擊上方“小白學視覺”&#xff0c;選擇加"星標"或“置頂”重磅干貨&#xff0c;第一時間送達一篇文章帶你了解4個最佳項目創意的代碼片段和示例Python是一種特殊的編程語言&#xff0c;適用于從初學者到中級用戶。由于它的靈活性&#xff0c;它正逐漸成為一種非常流…

Android 多狀態加載布局的開發 Tips

2019獨角獸企業重金招聘Python工程師標準>>> 什么是多狀態 Layout 對于大多數 App 而言&#xff0c;項目中都有多狀態加載 View 這種需求&#xff0c;如下圖所示。 對應到開發中&#xff0c;我們通常會開發一個對應的自定義 layout 用于根據頁面不同的狀態來顯示不同…

XML解析之JAXP案例詳解

根據一個CRUD的案例&#xff0c;對JAXP解析xml技術&#xff0c;進行詳細的解釋&#xff1a; 首先&#xff0c;已知一個xml文件中的數據如下&#xff1a; <?xml version"1.0" encoding"UTF-8" standalone"no"?> <書架><書 出版社…

隨機梯度下降

1.SGD 代價函數通常可以分解成每個樣本的代價函數的總和轉載于:https://www.cnblogs.com/bigcome/p/10042800.html