第一種:不採用連接池
package test0;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class test1 {
public static void main(String[] args) throws SQLException {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/vuldatabase","root","root");
System.out.println(con);
Statement st = con.createStatement();
String sql = "select * from sys_userinfo where id =1";
ResultSet re = st.executeQuery(sql);
while(re.next()){
System.out.println(re.getString("name"));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.sxf</groupId>
<artifactId>test</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.18</version>
</dependency>
</dependencies>
</project>
第二種:採用連接池
1、項目結構
2、配置文件 datasource.properties
classname=com.mysql.jdbc.Driver
url=jdbc:mysql://192.168.21.128:3306/vuldatabase?characterEncoding=utf-8
username=mmall
password=mmall
maxactive=300
maxwait=300000
3、DBCP(數據庫連接池)
package com.ydtf.ipcc.sms.util;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import java.io.InputStream;
import org.apache.commons.dbcp.BasicDataSource;
/**
* DBCP(數據庫連接池)
* @author Shixf
* @date 2018年5月4日
*/
public class DBUtil {
private static String classname;
private static String url;
private static String username;
private static String password;
private static int maxactive;
private static long maxwait;
private static BasicDataSource bds;
static{
try {
//讀取屬性文件 datasource.properties
Properties prop = new Properties();
ClassLoader classLoader = DBUtil.class.getClassLoader();
InputStream in = classLoader.getResourceAsStream("datasource.properties");
prop.load(in);
classname = prop.getProperty("classname");
url = prop.getProperty("url");
username = prop.getProperty("username");
password = prop.getProperty("password");
maxactive = Integer.parseInt(prop.getProperty("maxactive"));
maxwait = Long.parseLong(prop.getProperty("maxwait"));
//初始化連接池
bds = new BasicDataSource();
bds.setDriverClassName(classname);
bds.setUrl(url);
bds.setUsername(username);
bds.setPassword(password);
bds.setMaxActive(maxactive);
bds.setMaxWait(maxwait);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 獲取數據庫連接
* @throws Exception
*/
public static Connection getConnection() throws Exception{
try {
return bds.getConnection();
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
/**
* 關閉數據庫連接
*/
public static void close(Connection conn){
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
4、Dao層(舉例)
package com.ydtf.ipcc.sms.dao;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import com.ydtf.ipcc.sms.util.DBUtil;
import com.ydtf.ipcc.sms.util.DateUtil;
import com.ydtf.ipcc.sms.vo.SmsVo;
/**
* 連接數據庫,獲取內容
* @author Shixf
* @date 2018年5月4日
*/
public class SmsDao {
private static Logger logger = Logger.getLogger(SmsDao.class);
/**
* 從數據庫中獲取短信內容
* @return
*/
public List<SmsVo> getSmsContent() {
DateUtil dateUtil = new DateUtil();
List<SmsVo> smsVolist = new ArrayList<SmsVo>();
Connection conn = null;
try {
conn = DBUtil.getConnection();
String sql = "SELECT n.title,n.action_time,n.end_time,re.orgID,re.sendID,re.userID,re.type,re.id "
+ "FROM notify_notify n "
+ "JOIN notify_recipient re "
+ "WHERE re.isNotice =0 "
+ "and n.id=re.notifyID ";
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while(rs.next()){
SmsVo smsVo = new SmsVo();
smsVo.setTitle(rs.getString("title"));
smsVo.setActionTime(dateUtil.time2String(rs.getTimestamp("action_time")));
smsVo.setEndTime(dateUtil.time2String(rs.getTimestamp("end_time")));
smsVo.setOrgId(rs.getInt("orgID"));
smsVo.setUserId(rs.getInt("userID"));
smsVo.setType(rs.getInt("type"));
smsVo.setId(rs.getInt("id"));
smsVolist.add(smsVo);
}
return smsVolist;
} catch (Exception e) {
logger.error("從數據庫中獲取短信內容發生錯誤:" + e);
} finally {
DBUtil.close(conn);
}
return null;
}
/**
* 根據用戶id獲取短信接收人號碼
* @param userId 用戶id
* @return 用戶號碼
*/
public String getPhoneByUserId(int userId) {
String phone = null;
Connection conn = null;
try {
conn = DBUtil.getConnection();
String sql = "SELECT mobile FROM sys_userinfo WHERE id = ? ";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, userId);
ResultSet rs = ps.executeQuery();
while(rs.next()){
phone = rs.getString("mobile");
}
} catch (Exception e) {
logger.error("根據用戶id獲取短信接收人號碼發生錯誤:" + e);
} finally {
DBUtil.close(conn);
}
return phone;
}
/**
* 根據機構id獲取短信接收人號碼
* @param orgId 機構id
* @return 用戶號碼
*/
public List<String> getPhoneByOrgId(int orgId) {
List<String> phoneList = new ArrayList<String>();
Connection conn = null;
try {
conn = DBUtil.getConnection();
String sql = "SELECT mobile FROM sys_userinfo WHERE org_id = ? ";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, orgId);
ResultSet rs = ps.executeQuery();
while(rs.next()){
String phone = rs.getString("mobile");
phoneList.add(phone);
}
} catch (Exception e) {
logger.error("根據機構id獲取短信接收人號碼發生錯誤:" + e);
} finally {
DBUtil.close(conn);
}
return phoneList;
}
/**
* 根據opid獲取子orgId
* @param opid 機構父id
* @return 機構id
*/
public List<Integer> getOrgIdByOpid(int opid) {
List<Integer> orgIdList = new ArrayList<Integer>();
Connection conn = null;
try {
conn = DBUtil.getConnection();
String sql = "SELECT id FROM sys_orginfo WHERE parent_dep_id = ? ";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, opid);
ResultSet rs = ps.executeQuery();
while(rs.next()){
int orgId = rs.getInt("id");
orgIdList.add(orgId);
}
} catch (Exception e) {
e.printStackTrace();
logger.error("根據opid獲取子orgId發生錯誤:" + e);
} finally {
DBUtil.close(conn);
}
return orgIdList;
}
/**
* 更改短信狀態爲“已發送”
* @param id
*/
public void updateNoticeType(int id) {
Connection conn = null;
try {
conn = DBUtil.getConnection();
String sql = "UPDATE notify_recipient SET isNotice = ? WHERE id = ?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, 1);
ps.setInt(2, id);
ps.executeUpdate();
} catch (Exception e) {
logger.error("更改短信狀態發生錯誤:" + e);
} finally {
DBUtil.close(conn);
}
}
}