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

(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;

}

java与mysql的交互_java与数据库交互常用到的一些方法相关推荐

  1. java操作mysql导表_java导出数据库的全部表到excel

    本文实例为大家分享了java将某个数据库的表全部导出到excel中的方法,供大家参考,具体内容如下 第一步:如何用POI操作Excel @Test public void createXls() th ...

  2. java与mysql笔试题_JAVA和数据库笔试题

    java部分: 选择:1.下面的执行结果: Java代码 public class Test3 { public static void main(String args[]){ int a=222; ...

  3. java 连接mysql工具类_java连接Mysql数据库的工具类

    一个封装好的链接Mysql数据库的工具类,可以方便的获取Connection对象关闭Statement.ResultSet.Statment对象等等 复制代码 代码如下: package myUtil ...

  4. java中mysql中标点符号_java – 如何在使用JDBC从MySQL数据库中提取数据时避免丢失标点符号?...

    首先,我正在使用: Java 1.7.0_02 MySQL 5.1.50 ZendServer CE (if that matters) 我用来从Java连接到MySQL的JDBC驱动程序是com.m ...

  5. java连接mysql 不推荐_java连接mysql

    看了一阵 spring 框架,不怎么好懂,最近脑子也有点不够用,于是乎来点简单的,用java连接数据库玩玩,顺便回顾一下数据库的增删改查~ 使用的是 eclipse .创建了个项目,然后网上找了篇教程 ...

  6. mysql 使用java代码进行操作系统_【MySQL 05】使用Java对MySQL进行操作(创建数据库)...

    JDBC连接数据库: 1.加载JDBC驱动程序 2.提供JDBC连接的URL 3.创建数据库的连接 4.创建一个Statement 5.执行SQL语句 6.处理结果 7.关闭JDBC对象 1.加载JD ...

  7. 帆软报表调用mysql存储过程_FineReport单行与数据库交互的方法

    FineReport单行与数据库交互的方法 1.   问题描述 我们在做一张报表填报的时候经常会遇到需要在一行进行添加动作,将该行数据直接与数据库交互,执行存储过程过程.我们可以通过每一行增加帆软&q ...

  8. java获取mysql时间格式化_Java与mysql的时间格式化问题,获取时间的上下午

    Java与mysql的时间格式化问题,获取时间的上下午java 在项目中常常会遇到对时间进行格式化的问题,一次在对应用中发现,使用Java的SimpleDateFormat格式化时间,获取到的是上午, ...

  9. java的mysql语句规范_JAVA语言编程格式高级规范

    作为一位开发人员,都要有严格的代码规范.为此我总结了一些代码规范案例. 目 录 1. 前言 2. 试用范围 3. JAVA命名规范-- 3.1 公共约定 3.2 Java文件.包 3.3 类.接口命名 ...

最新文章

  1. 神奇的 SQL,Group By 真扎心,原来是这样!
  2. 如何在asp.net mvc3中使用HttpStatusCode
  3. 用了这么多年 curl,竟然不知道还有这种用法?!
  4. python【Pandas科学计算库】连女朋友都会用的Pandas(真の能看懂~!)
  5. 设置更改root密码 连接mysql mysql常用命令
  6. 一个通过Flash设计与Flex结合开发的网站www.mapgle.cn
  7. netty系列之:使用netty搭建websocket客户端
  8. python编写简单赌博游戏赏析及注意事项
  9. Java 基础之java运算符
  10. idea 导入template_如何将静态导入添加到IntelliJ IDEA实时模板
  11. 在mybatis里面设置不同数据库运行环境和适应性问题
  12. PHP连接MSSQL数据库案例,PHPWAMP多个PHP版本连接SQL Server数据库
  13. java 聊天室源代码_java聊天室源码(含客户端、服务端)
  14. React子组件给父组件传值
  15. 详解sklearn——CountVectorizer
  16. 广东中考可以用计算机吗,广州中考改革迎五大变革:中考禁用计算机 详细新政一览...
  17. 概率论复习笔记——条件概率、全概率、贝叶斯公式及其应用
  18. 李元佳:漫谈 Greenplum 开源背后的动机
  19. Android | 如何计算图片占用内存的大小
  20. c语言关键字中英翻译机课程设计,课程设计--C语言关键字中英翻译机.doc

热门文章

  1. CSS外边距(margin)重叠及防止方法
  2. android项目方法数超过65536的解决办法
  3. python 3 面向过程编程
  4. socket websocket
  5. 使用GNS3和Cisco IOU搭建路由交换实验-安装篇
  6. Eclipse3.7 Indigo 字体设置为Courier New
  7. Etherchannel的配置 三层
  8. 学习笔记----linux下编译samba
  9. 5895. 获取单值网格的最小操作数
  10. 如何在React Native中使用react-navigation 5处理导航