源码:https://github.com/xiaostudy/jdbc_test1

这是没有使用连接池的

目录

创建的sql语句create.sql

 DROP TABLE IF EXISTS t_user;

 CREATE TABLE t_user(
id INT(11) PRIMARY KEY AUTO_INCREMENT,
user_name VARCHAR(20) NOT NULL DEFAULT "",
password VARCHAR(20) NOT NULL DEFAULT ""
)ENGINE = INNODB DEFAULT CHARSET = utf8 COMMENT = '用户表';

maven配置pom.xml

 <?xml version="1.0" encoding="UTF-8"?>
<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.xiaostudy</groupId>
<artifactId>jdbc_test1</artifactId>
<version>1.0.0</version> <properties>
<jdbc.version>5.1.46</jdbc.version>
</properties> <dependencies>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${jdbc.version}</version>
</dependency>
</dependencies>
</project>

Base实体类User.java

 package com.xiaostudy.Base;

 /**
* Created with IntelliJ IDEA.
* User: Administrator
* Date: 2019/5/4
* Time: 12:10
* Description: No Description
*/
public class User { private Integer id;
private String userName;
private String password; public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getUserName() {
return userName;
} public void setUserName(String userName) {
this.userName = userName;
} public String getPassword() {
return password;
} public void setPassword(String password) {
this.password = password;
} @Override
public String toString() {
return "User{" +
"id=" + id +
", userName='" + userName + '\'' +
", password='" + password + '\'' +
'}';
}
}

mysql连接配置db.properties

 driver = com.mysql.jdbc.Driver
url = jdbc:mysql://localhost:3306/lw_test?useUnicode=true&characterEncoding=UTF-8
userName = root
password = root

重点,jdbc配置JdbcUtil.java

 package com.xiaostudy.util;

 import java.io.FileInputStream;
import java.io.IOException;
import java.sql.*;
import java.util.Properties; /**
* Created with IntelliJ IDEA.
* User: xiaostudy
* Date: 2019/5/4
* Time: 11:58
* Description: No Description
*/
public class JdbcUtil { private static Connection connection; public static Connection getConnection() {
if(null != connection) {
return connection;
} Properties pt = new Properties();
try {
FileInputStream fis = new FileInputStream("src\\main\\resources\\db.properties");
pt.load(fis);
} catch (IOException e) {
e.printStackTrace();
}
String driver = pt.getProperty("driver");
String url = pt.getProperty("url");
String userName = pt.getProperty("userName");
String password = pt.getProperty("password"); if(null == driver || null == url || null == userName || null == password) {
return null;
} Connection conn = null;
try {
Class.forName(driver); //classLoader,加载对应驱动
conn = DriverManager.getConnection(url, userName, password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
} public static void close(PreparedStatement pstmt, Connection conn,ResultSet rs) {
try {
if(null != rs) {
rs.close();
rs = null;
}
if(null != pstmt) {
pstmt.close();
pstmt = null;
}
if(null != conn) {
conn.close();
conn = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}

操作数据库UserDao.java

 package com.xiaostudy.dao;

 import com.xiaostudy.Base.User;
import com.xiaostudy.util.JdbcUtil;
import com.xiaostudy.util.MyDataSource; import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List; /**
* Created with IntelliJ IDEA.
* User: xiaostudy
* Date: 2019/5/4
* Time: 16:47
* Description: No Description
*/
public class UserDao { public int insert(User user) {
if(null == user) {
return 0;
} Connection conn = JdbcUtil.getConnection();
if(null == conn) {
return 0;
} int i = 0;
String sql = "insert into t_user (user_name,password) values(?,?)";
PreparedStatement pstmt = null;
try {
pstmt = (PreparedStatement) conn.prepareStatement(sql);
pstmt.setString(1, user.getUserName());
pstmt.setString(2, user.getPassword());
i = pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
JdbcUtil.close(pstmt, conn, null);
}
return i;
} public int update(User user) {
if(null == user || null == user.getId() || user.getId() <= 0) {
return 0;
} Connection conn = JdbcUtil.getConnection();
if(null == conn) {
return 0;
} int i = 0;
String sql = "update t_user set user_name='" + user.getUserName() + "', password='" + user.getPassword() + "' where id='" + user.getId() + "' ";
PreparedStatement pstmt = null;
try {
pstmt = (PreparedStatement) conn.prepareStatement(sql);
i = pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
JdbcUtil.close(pstmt, conn, null);
}
return i;
} public List<User> getAll() {
List<User> list = new ArrayList<User>();
Connection conn = JdbcUtil.getConnection();
if(null == conn) {
return list;
} String sql = "select id, user_name, password from t_user";
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
pstmt = (PreparedStatement)conn.prepareStatement(sql);
rs = pstmt.executeQuery();
while (rs.next()) {
User user = new User();
user.setId(rs.getInt(1));
user.setUserName(rs.getString("user_name"));
user.setPassword(rs.getString("password"));
list.add(user);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
JdbcUtil.close(pstmt, conn, rs);
}
return list;
} public User getUserByUserName(String userName) {
if(null == userName || userName.trim().length() <= 0) {
return null;
} Connection conn = JdbcUtil.getConnection();
if(null == conn) {
return null;
} User user = new User();
String sql = "select id, user_name, password from t_user where user_name='" + userName + "'";
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
pstmt = (PreparedStatement)conn.prepareStatement(sql);
rs = pstmt.executeQuery();
while (rs.next()) {
user.setId(rs.getInt(1));
user.setUserName(rs.getString("user_name"));
user.setPassword(rs.getString("password"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
JdbcUtil.close(pstmt, conn, rs);
}
return user;
} public int delete(String userName) {
if(null == userName || userName.trim().length() <= 0) {
return 0;
} Connection conn = JdbcUtil.getConnection();
if(null == conn) {
return 0;
} int i = 0;
String sql = "delete from t_user where user_name='" + userName + "'";
PreparedStatement pstmt = null;
try {
pstmt = (PreparedStatement) conn.prepareStatement(sql);
i = pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
JdbcUtil.close(pstmt, conn, null);
}
return i;
}
}

测试Test_jdbc.java

 package com.xiaostudy.test;

 import com.xiaostudy.Base.User;
import com.xiaostudy.dao.UserDao;
import com.xiaostudy.util.JdbcUtil; import java.util.List; /**
* Created with IntelliJ IDEA.
* User: Administrator
* Date: 2019/5/4
* Time: 15:05
* Description: No Description
*/
public class Test_jdbc { public static void main(String[] agrs) {
UserDao userDao = new UserDao(); //查询全部用户
List<User> list = userDao.getAll();
System.out.println(list);
//查询某个用户名下的用户
// User user = userDao.getUserByUserName("张三");
// System.out.println(user); // 新建用户
// User user = new User();
// user.setUserName("张三");
// user.setPassword("123");
// int insert = userDao.insert(user);
// System.out.println(insert); //新建用户
// User user = new User();
// user.setUserName("李四");
// user.setPassword("123444");
// int insert = userDao.insert(user);
// System.out.println(insert); //删除用户
// int i = userDao.delete("李四");
// System.out.println(i); //修改用户
// User user = userDao.getUserByUserName("李四");
// user.setPassword("1995");
// int i = userDao.update(user);
// System.out.println(i); // list = userDao.getAll();
// System.out.println(list);
}
}

以下是使用自定义的连接池

目录

自定义的连接池MyDataSource.java

 package com.xiaostudy.util;

 import java.io.PrintWriter;
import java.sql.*;
import java.util.LinkedList;
import java.util.logging.Logger; import javax.sql.DataSource; public class MyDataSource implements DataSource {
private static LinkedList<Connection> pool=new LinkedList<Connection>();
static{
for (int i = 0; i < 5; i++) {
Connection conn=JdbcUtil.getConnection();
pool.add(conn);
}
} @Override
public Connection getConnection() throws SQLException {
Connection conn=null;
if (0 == pool.size()) {
for (int i = 0; i < 5; i++) {
conn=JdbcUtil.getConnection();
pool.add(conn);
}
}
conn=pool.remove(0);
return conn;
} public static void close(Connection conn){
pool.add(conn);
} public static void close(PreparedStatement pstmt, Connection conn, ResultSet rs) {
if(null != conn) {
pool.add(conn);
}
JdbcUtil.close(pstmt, null, rs);
} @Override
public PrintWriter getLogWriter() throws SQLException {
return null;
} @Override
public int getLoginTimeout() throws SQLException {
// TODO Auto-generated method stub
return 0;
} @Override
public Logger getParentLogger() throws SQLFeatureNotSupportedException {
// TODO Auto-generated method stub
return null;
} @Override
public void setLogWriter(PrintWriter arg0) throws SQLException {
// TODO Auto-generated method stub } @Override
public void setLoginTimeout(int arg0) throws SQLException {
// TODO Auto-generated method stub } @Override
public boolean isWrapperFor(Class<?> arg0) throws SQLException {
// TODO Auto-generated method stub
return false;
} @Override
public <T> T unwrap(Class<T> arg0) throws SQLException {
// TODO Auto-generated method stub
return null;
} @Override
public Connection getConnection(String arg0, String arg1)
throws SQLException { return null;
} }

使用连接池的dao,UserDao_MyDataSource.java

 package com.xiaostudy.dao;

 import com.xiaostudy.Base.User;
import com.xiaostudy.util.MyDataSource; import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List; /**
* Created with IntelliJ IDEA.
* User: xiaostudy
* Date: 2019/5/4
* Time: 16:47
* Description: No Description
*/
public class UserDao_MyDataSource { private static MyDataSource myDataSource; static {
myDataSource = new MyDataSource();
} public int insert(User user) {
if(null == user) {
return 0;
} Connection conn = null;
try {
conn = myDataSource.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
if(null == conn) {
return 0;
} int i = 0;
String sql = "insert into t_user (user_name,password) values(?,?)";
PreparedStatement pstmt = null;
try {
pstmt = (PreparedStatement) conn.prepareStatement(sql);
pstmt.setString(1, user.getUserName());
pstmt.setString(2, user.getPassword());
i = pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
MyDataSource.close(pstmt, conn, null);
}
return i;
} public int update(User user) {
if(null == user || null == user.getId() || user.getId() <= 0) {
return 0;
} Connection conn = null;
try {
conn = myDataSource.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
if(null == conn) {
return 0;
} int i = 0;
String sql = "update t_user set user_name='" + user.getUserName() + "', password='" + user.getPassword() + "' where id='" + user.getId() + "' ";
PreparedStatement pstmt = null;
try {
pstmt = (PreparedStatement) conn.prepareStatement(sql);
i = pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
MyDataSource.close(pstmt, conn, null);
}
return i;
} public List<User> getAll() {
List<User> list = new ArrayList<User>();
Connection conn = null;
try {
conn = myDataSource.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
if(null == conn) {
return list;
} String sql = "select id, user_name, password from t_user";
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
pstmt = (PreparedStatement)conn.prepareStatement(sql);
rs = pstmt.executeQuery();
while (rs.next()) {
User user = new User();
user.setId(rs.getInt(1));
user.setUserName(rs.getString("user_name"));
user.setPassword(rs.getString("password"));
list.add(user);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
MyDataSource.close(pstmt, conn, rs);
}
return list;
} public User getUserByUserName(String userName) {
if(null == userName || userName.trim().length() <= 0) {
return null;
} Connection conn = null;
try {
conn = myDataSource.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
if(null == conn) {
return null;
} User user = new User();
String sql = "select id, user_name, password from t_user where user_name='" + userName + "'";
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
pstmt = (PreparedStatement)conn.prepareStatement(sql);
rs = pstmt.executeQuery();
while (rs.next()) {
user.setId(rs.getInt(1));
user.setUserName(rs.getString("user_name"));
user.setPassword(rs.getString("password"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
MyDataSource.close(pstmt, conn, rs);
}
return user;
} public int delete(String userName) {
if(null == userName || userName.trim().length() <= 0) {
return 0;
} Connection conn = null;
try {
conn = myDataSource.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
if(null == conn) {
return 0;
} int i = 0;
String sql = "delete from t_user where user_name='" + userName + "'";
PreparedStatement pstmt = null;
try {
pstmt = (PreparedStatement) conn.prepareStatement(sql);
i = pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
MyDataSource.close(pstmt, conn, null);
}
return i;
}
}

测试,就是把之前的

UserDao userDao = new UserDao();
换成
UserDao_MyDataSource userDao = new UserDao_MyDataSource();
 package com.xiaostudy.test;

 import com.xiaostudy.Base.User;
import com.xiaostudy.dao.UserDao_MyDataSource; import java.util.List; /**
* Created with IntelliJ IDEA.
* User: Administrator
* Date: 2019/5/4
* Time: 15:05
* Description: No Description
*/
public class Test_jdbc2 { public static void main(String[] agrs) {
UserDao_MyDataSource userDao = new UserDao_MyDataSource(); //查询全部用户
List<User> list = userDao.getAll();
System.out.println(list);
//查询某个用户名下的用户
// User user = userDao.getUserByUserName("张三");
// System.out.println(user); // 新建用户
// User user = new User();
// user.setUserName("张三");
// user.setPassword("123");
// int insert = userDao.insert(user);
// System.out.println(insert); //新建用户
// User user = new User();
// user.setUserName("李四");
// user.setPassword("123444");
// int insert = userDao.insert(user);
// System.out.println(insert); //删除用户
// int i = userDao.delete("李四");
// System.out.println(i); //修改用户
// User user = userDao.getUserByUserName("李四");
// user.setPassword("1995");
// int i = userDao.update(user);
// System.out.println(i); // list = userDao.getAll();
// System.out.println(list);
}
}

jdbc配置及使用测试的更多相关文章

  1. 用IntelliJ IDEA 开发Spring+SpringMVC+Mybatis框架 分步搭建三:配置spring并测试

    这一部分的主要目的是 配置spring-service.xml  也就是配置spring  并测试service层 是否配置成功 用IntelliJ IDEA 开发Spring+SpringMVC+M ...

  2. 用IntelliJ IDEA 开发Spring+SpringMVC+Mybatis框架 分步搭建二:配置MyBatis 并测试(2 配置spring-dao和测试)

    用IntelliJ IDEA 开发Spring+SpringMVC+Mybatis框架 分步搭建二:配置MyBatis 并测试(1 搭建目录环境和依赖) 四:在\resources\spring 下面 ...

  3. spark之JDBC开发(连接数据库测试)

    spark之JDBC开发(连接数据库测试) 以下操作属于本地模式操作: 1.在Eclipse4.5中建立工程RDDToJDBC,并创建一个文件夹lib用于放置第三方驱动包 [hadoop@CloudD ...

  4. jdbc 配置

    jdbc 配置 Class.forName("com.mysql.jdbc.Driver")  ;//加载数据库驱动 Connection conn=null; String ur ...

  5. 用IntelliJ IDEA 开发Spring+SpringMVC+Mybatis框架 分步搭建二:配置MyBatis 并测试(1 构建目录环境和依赖)

    引言:在用IntelliJ IDEA 开发Spring+SpringMVC+Mybatis框架 分步搭建一   的基础上 继续进行项目搭建 该部分的主要目的是测通MyBatis 及Spring-dao ...

  6. spring BasicDataSource 数据源配置 sqlserver数据库 oracle数据库 mysql数据jdbc配置

    spring BasicDataSource 数据源配置 sqlserver数据库 oracle数据库 mysql数据jdbc配置 jdbc.properties 文件信息如下: ---------- ...

  7. spring-注解配置-junit整合测试-aop

    1 使用注解配置spring 1.1 步骤 导包4+2+spring-aop 1.为主配置文件引入新的命名空间(约束) 2.开启使用注解代理配置文件 3.在类中使用注解完成配置 1.2 将对象注册到容 ...

  8. Jmeter JDBC配置

    前提条件,驱动包mysql-connector-java-5.1.38-bin.jar要放到本机Java路径:C:\Program Files\Java\jdk1.8.0_73\jre\lib\ext ...

  9. elasticsearch logstash jdbc 配置 增量更新

    环境前提: centos 6.5 x64 jdk 1.8 elasticsearch 6.1.4 logstash 6.1.4 kibana 6.1.4 mysql 5.x 保证上面软件已经安装,并且 ...

随机推荐

  1. session.getdefaultinstance和getinstance的区别

    如果想要同时使用两个帐号发送javamail,比如使用1@a.com发送1#邮件,使用2@a.com发送2#邮件,这时候,你就需要同时创建两个java.mail.Session对象.但是如果你仍然使用 ...

  2. [Luogu] 打砖块

    题面:https://www.luogu.org/problemnew/show/P1174 题解:https://www.zybuluo.com/wsndy-xx/note/1145569

  3. sigaction()函数

    sigaction函数 修改信号处理动作(通常在Linux用其来注册一个信号的捕捉函数) int sigaction(int signum, const struct sigaction *act, ...

  4. 将省市县三级联动的json数据,转化为element-ui能用的格式,并使用

    var options=[]; var cities = { '北京': { '北京': ['东城区', '西城区', '崇文区', '宣武区', '朝阳区', '丰台区', '石景山区', '海淀区 ...

  5. idea将项目打成jar包

    在用jmeter做压测时,需要将项目打成jar包放至在如下目录 /Users/admin/Documents/software/apache-jmeter-5.1.1/apache-jmeter-5. ...

  6. Qt读写Json格式配置文件

    头文件Config.h #pragma once #include <QVariantMap> class Config { public: Config(const QString &a ...

  7. JavaWeb_(Spring框架)整合Mybatis加入事务操作数据库

    整合Mybatis a)导包: i.Spring:基本包.aop.aspects.jdbc.tx.test: ii.Mybatis:mybatis-3.4.6 iii.整合包:mybatis-spri ...

  8. jenkins创建工程

    1.新建一个工程 2.添加工程名,点击创建一个自由分格的软件项目 3.配置源码管理 4.增加工程构建步骤,选中调用顶层maven目标

  9. Java并发指南2:深入理解Java内存模型JMM

    本文转载自互联网,侵删   一:JMM基础与happens-before 并发编程模型的分类 在并发编程中,我们需要处理两个关键问题:线程之间如何通信及线程之间如何同步(这里的线程是指并发执行的活动实 ...

  10. pwn学习日记Day18 《程序员的自我修养》读书笔记

    知识杂项 obj文件:当前源代码编译成二进制目标文件 exe文件:将.obj文件与库文件.lib等文件链接生成的可执行文件 一个现代编译器的主要工作流程如下: 源程序(source code)→ 预处 ...