package com.javaweb.mvc;

import java.sql.*;

/**
* @author 公共数据访问类
*
* Statement 和 PreparedStatement之间的关系和区别
* 关系:PreparedStatement继承自Statement,都是接口
* 区别:PreparedStatement可以使用占位符,是预编译的,批处理比Statement效率高
* 注意:Statement执行SQL语句有SQL注入,一般不使用
*
*/
public class SqlHelper {
private static String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
private static String dbURL = "jdbc:sqlserver://mssql-rw-cyp_coopbusiness.vip.test.suixinhuan.com;DatabaseName=CYP_CoopBusiness";
private static String userName = "sa";
private static String userPwd = ""; private static Connection getCoonection()
{
Connection conn = null;
try
{
// 加载JDBC驱动
Class.forName(driverName);
// 获取连接
conn = DriverManager.getConnection(dbURL, userName, userPwd);
return conn;
}
catch(Exception e)
{
e.printStackTrace();
}
return null;
} /**
* PreparedStatement执行查询操作
* @param SQL
* @param args
* @return
*/
public static ResultSet executeQuery(String SQL, Object[] args)
{
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try
{
conn = getCoonection();
ps = conn.prepareStatement(SQL);
// 设置参数
if (args != null && args.length > ) {
for (int i = ; i < args.length; i++) {
ps.setObject(i + , args[i]);
}
}
rs = ps.executeQuery();
return rs;
}
catch(Exception e)
{
e.printStackTrace();
}
finally {
try {
if (rs != null)
rs.close();
if (ps != null)
ps.close();
if (conn != null)
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return null;
} /**
* PreparedStatement执行增删改操作
* @param SQL
* @param args
* @return
*/
public static boolean executeUpdate(String SQL, Object[] args)
{
Connection conn = null;
PreparedStatement ps = null;
try
{
conn = getCoonection();
ps = conn.prepareStatement(SQL);
// 设置参数
if (args != null && args.length > ) {
for (int i = ; i < args.length; i++) {
ps.setObject(i + , args[i]);
}
}
int result = ps.executeUpdate(); //返回受影响的行数
if(result > )
return true;
}
catch(Exception e)
{
e.printStackTrace();
}
finally {
try {
if (ps != null)
ps.close();
if (conn != null)
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return false;
} /**
* Statement执行查询操作
* @param SQL
* @return
*/
public static ResultSet executeQuery(String SQL)
{
Connection conn = null;
Statement sm = null;
ResultSet rs = null;
try
{
conn = getCoonection();
sm = conn.createStatement();
rs = sm.executeQuery(SQL);
return rs;
}
catch(Exception e)
{
e.printStackTrace();
}
finally {
try {
if (rs != null)
rs.close();
if (sm != null)
sm.close();
if (conn != null)
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return null;
} /**
* Statement执行增删改操作
* @param SQL
* @return
*/
public static boolean executeUpdate(String SQL)
{
Connection conn = null;
Statement sm = null;
try
{
conn = getCoonection();
sm = conn.createStatement();
int result = sm.executeUpdate(SQL); //返回受影响的行数
if(result > )
return true;
}
catch(Exception e)
{
e.printStackTrace();
}
finally {
try {
if (sm != null)
sm.close();
if (conn != null)
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return false;
}
}

下面是调用实例:

package com.javaweb.mvc;

import java.util.ArrayList;
import java.util.List;
import java.sql.*; /**
* @author 数据访问类
*
*/
public class ServiceStationDao {
/**
* @return 查询所有服务站
*
*/
public List<ServiceStation> getAll() {
List<ServiceStation> list = new ArrayList<ServiceStation>();
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null; try { // 加载JDBC驱动
// Class.forName("com.mysql.jdbc.Driver");
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); // 连接服务器和数据库
// String url = "jdbc:mysql://localhost:3306/student?user=root&password=1234";
String url = "jdbc:sqlserver://mssql-rw-cyp_coopbusiness.vip.test.suixinhuan.com;DatabaseName=CYP_CoopBusiness";
String user = "Umanager";
String password = "ASD123asd!1";
String sql = "SELECT ROW_NUMBER() over(order by CreateDate) as RowNum,* FROM T_TRA_ServiceStation WHERE DeleteTag = 0 AND CityCode = ? ORDER BY CreateDate";
conn = DriverManager.getConnection(url, user, password);
ps = conn.prepareStatement(sql);
ps.setString(, "");
rs = ps.executeQuery();
while (rs.next()) {
int RowNum = rs.getInt();
String ID = rs.getString();
String StationName = rs.getString("StationName");
String CityCode = rs.getString("CityCode");
String CityName = rs.getString("CityName");
String StationAddr = rs.getString("StationAddr");
int IsEnabled = rs.getInt("IsEnabled");
String Createor = rs.getString("Createor");
String strCreateDate = rs.getString("CreateDate");
java.util.Date CreateDate = CommonHelper.strToDateLong(strCreateDate); ServiceStation obj = new ServiceStation(RowNum, ID, StationName, CityCode, CityName, StationAddr,
IsEnabled, Createor, CreateDate);
list.add(obj);
}
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
catch (SQLException e) {
e.printStackTrace();
}
finally {
try {
if (rs != null)
rs.close();
if (ps != null)
ps.close();
if (conn != null)
conn.close();
}
catch (SQLException e) {
e.printStackTrace();
}
}
return list;
} /**
* @return 新增服务站
*
*/
public boolean addServiceStation(ServiceStation obj) {
// //方式一
// String SQL = "INSERT INTO dbo.T_TRA_ServiceStation (ID,StationName,CityCode,CityName,StationAddr,Lng,lat,IsEnabled,Createor,DeleteTag,CreateorUser,CreateDate,LastOperName,LastOperUser,LastOperDate)";
// SQL += " VALUES ('598212333755587533', '"+obj.getStationName()+"', '110100', '北京-北京市', '"+obj.getStationAddr()+"', 116.420574, 40.012993, 0, 'System', 0, 'System', '"+CommonHelper.getStringDate()+"', 'zhouruibj', '周锐北京', '"+CommonHelper.dateToStrLong(obj.getCreateDate())+"')";
// boolean result = SqlHelper.executeUpdate(SQL);
//方式二
String SQL = "INSERT INTO dbo.T_TRA_ServiceStation VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
Object[] args = new Object[];
args[] = CommonHelper.getCard() + CommonHelper.getCard();
args[] = obj.getStationName();
args[] = "";
args[] = "北京-北京市";
args[] = obj.getStationAddr();
args[] = 116.420574;
args[] = 40.012993;
args[] = ;
args[] = "System";
args[] = ;
args[] = "System";
args[] = CommonHelper.getStringDate();
args[] = "zhouruibj";
args[] = "周锐北京";
args[] = CommonHelper.dateToStrLong(obj.getCreateDate());
boolean result = SqlHelper.executeUpdate(SQL, args);
return result;
} /**
* @return 删除服务站
*
*/
public boolean deleteServiceStation(String ID)
{
String SQL = "DELETE FROM T_TRA_ServiceStation WHERE ID = ?";
Object[] args = new Object[];
args[] = ID;
boolean result = SqlHelper.executeUpdate(SQL, args);
return result;
}
}

java 访问数据库公共类的更多相关文章

  1. JavaSE学习总结(九)—— Java访问数据库(JDBC)

    一.JDBC简介 JDBC(Java Data Base Connectivity,java数据库连接)是一种用于执行SQL语句的Java API,可以为多种关系数据库提供统一访问,它由一组用Java ...

  2. Java访问数据库Mysql

    一.概述 本文主要介绍Java接连数据库的基本方法和步骤,并对其中的几个要点进行简要说明. 二.数据库访问步骤 在Java中连接数据库进行的访问主要有以下几个步骤: 加载数据库驱动 注册数据库驱动 建 ...

  3. oracle 事务简介,锁的概念,java访问数据库注意事项

    java链接oracle和连接其他数据库一样有两种方式:1 桥接 jdbc-obdc2 jbdc insert语句一次插入大量数据 insert into table (列1,列2,列3) selec ...

  4. java访问数据库步骤详解

    eg1: public static void main(String[] args) throws ClassNotFoundException, SQLException { //第一步:加载JD ...

  5. java访问数据库被拒绝,不能连接数据库ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)

    错误原因:mysql数据库只允许本地ip访问: 解决方法:修改mysql表设置所有ip都可以访问: 登录数据库 使用以下命令: use mysql; grant all privileges on * ...

  6. java 访问数据库

    Class.forName(“com.microsoft.sqlserver.jdbc.SQLServerDriver”);//依据不同数据库,加载不同驱动 String url = “jdbc:sq ...

  7. 三国武将查询系统 //Java 访问 数据库

    import java.awt.*; import javax.swing.*; import java.awt.event.ActionListener; import java.awt.event ...

  8. java访问数据库的sql

    drop database if exists STOREDB;create database STOREDB;use STOREDB; create table CUSTOMERS ( ID big ...

  9. Java课程设计---数据库工具类

    接下来看看传统的查询方式(一个完整的查询) package com.java.mysql; import java.sql.Connection; import java.sql.DriverMana ...

随机推荐

  1. python的logging日志模块(二)

    晚上比较懒,直接搬砖了. 1.简单的将日志打印到屏幕   import logging logging.debug('This is debug message') logging.info('Thi ...

  2. 常见http响应状态码(status)

    1.100-199信息响应 100 Continue: 服务器通知浏览器之前一切正常,请客户端继续请求,如果请求结束,可忽略: 101 Switching Protocal: 针对请求头的Upgrad ...

  3. Codeforces Educational Codeforces Round 67

    目录 Contest Info Solutions A. Stickers and Toys B. Letters Shop C. Vasya And Array D. Subarray Sortin ...

  4. (转)初试 Netflix 开源持续云交付平台 Spinnaker

    目录 Spinnaker 介绍 环境.软件准备 安装 Development Spinnaker 配置依赖环境 配置并安装 Spinnaker 演示 Spinnaker Pipeline 演示 Spi ...

  5. 手写alert弹框(一)

    采用原生的JavaScript, html代码 <meta name="viewport" content="width=device-width, initial ...

  6. intel官方的手册

    最近在学习汇编语言,需要用到intel的手册,无论是csdn还是其他的,都要下载币,还不便宜,也很老的资料了. 直接到这个地址:https://software.intel.com/en-us/art ...

  7. WINRAR弹窗堆栈

    0:000> db 004ddfa8004ddfa8 6f 00 70 00 65 00 6e 00-00 00 00 00 2d 00 6e 00 o.p.e.n.....-.n. 03063 ...

  8. [.NET] ConfuserEx脱壳工具打包

    [.NET] ConfuserEx脱壳工具打包 ConfuserEx 1.0.0脱壳步骤        Written by 今夕何夕[W.B.L.E. TeAm] 1.先用UnconfuserEx把 ...

  9. Understanding Models, Views, and Controllers (C#)

    https://docs.microsoft.com/en-us/aspnet/mvc/overview/older-versions-1/overview/understanding-models- ...

  10. 跨平台(win和unix)的线程封装类

    #ifdef WIN32 #include <Windows.h> #include <process.h> #else #include <pthread.h> ...