下面我整理了一下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