jdbc配置及使用测试
源码: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配置及使用测试的更多相关文章
- 用IntelliJ IDEA 开发Spring+SpringMVC+Mybatis框架 分步搭建三:配置spring并测试
这一部分的主要目的是 配置spring-service.xml 也就是配置spring 并测试service层 是否配置成功 用IntelliJ IDEA 开发Spring+SpringMVC+M ...
- 用IntelliJ IDEA 开发Spring+SpringMVC+Mybatis框架 分步搭建二:配置MyBatis 并测试(2 配置spring-dao和测试)
用IntelliJ IDEA 开发Spring+SpringMVC+Mybatis框架 分步搭建二:配置MyBatis 并测试(1 搭建目录环境和依赖) 四:在\resources\spring 下面 ...
- spark之JDBC开发(连接数据库测试)
spark之JDBC开发(连接数据库测试) 以下操作属于本地模式操作: 1.在Eclipse4.5中建立工程RDDToJDBC,并创建一个文件夹lib用于放置第三方驱动包 [hadoop@CloudD ...
- jdbc 配置
jdbc 配置 Class.forName("com.mysql.jdbc.Driver") ;//加载数据库驱动 Connection conn=null; String ur ...
- 用IntelliJ IDEA 开发Spring+SpringMVC+Mybatis框架 分步搭建二:配置MyBatis 并测试(1 构建目录环境和依赖)
引言:在用IntelliJ IDEA 开发Spring+SpringMVC+Mybatis框架 分步搭建一 的基础上 继续进行项目搭建 该部分的主要目的是测通MyBatis 及Spring-dao ...
- spring BasicDataSource 数据源配置 sqlserver数据库 oracle数据库 mysql数据jdbc配置
spring BasicDataSource 数据源配置 sqlserver数据库 oracle数据库 mysql数据jdbc配置 jdbc.properties 文件信息如下: ---------- ...
- spring-注解配置-junit整合测试-aop
1 使用注解配置spring 1.1 步骤 导包4+2+spring-aop 1.为主配置文件引入新的命名空间(约束) 2.开启使用注解代理配置文件 3.在类中使用注解完成配置 1.2 将对象注册到容 ...
- Jmeter JDBC配置
前提条件,驱动包mysql-connector-java-5.1.38-bin.jar要放到本机Java路径:C:\Program Files\Java\jdk1.8.0_73\jre\lib\ext ...
- 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 保证上面软件已经安装,并且 ...
随机推荐
- 【算法题目】Leetcode算法题思路:两数相加
在LeetCode上刷了一题比较基础的算法题,一开始也能解出来,不过在解题过程中用了比较多的if判断,看起来代码比较差,经过思考和改进把原来的算法优化了. 题目: 给出两个 非空 的链表用来表示两个非 ...
- 004_FreeRTOS创建与删除任务
(一)创建与删除任务函数 (二)上面的四个函数目前只用动态创建任务和删除任务 (三)动态创建任务 函数 xTaxkCreate() 1. 宏 configSUPPORT_DYNAMIC_ALLOCAT ...
- java获取一段字符串里符合日期的正则表达式的字符串
import java.util.regex.Matcher; import java.util.regex.Pattern; public class Test3 { public static v ...
- myeclipse打开jsp后死掉,或变卡的问题
很多小伙伴在myeclipse下打开jsp会特别卡,甚至会卡死掉,我也遇到过很多次这种情况,下面分享一下解决方法: 1,打开 Window -> Preferences -> Genera ...
- Noip2011 提高组 选择客栈
P1311 选择客栈 直通 思路: ①看题,我们可以发现一个显然的性质,即当最左边的客栈向右移动时,最右边的客栈时单调向右的,并且右端点往右的客栈也符合要求.(因为只要左侧有一个满足的,右边的自然可以 ...
- gcc 带参数进行编译
gcc -DYES -o helloyes hello.c 在hello.c中存在 #ifdefine YES ........
- SIGCHLD函数
SIGCHLD的产生条件 子进程终止时 子进程接收到SIGSTOP信号停止时 子进程处在停止态,接受到SIGCONT后唤醒时 借助SIGCHLD信号回收子进程 子进程结束运行,其父进程会收到SIGCH ...
- D3DFVF_XYZ和D3DFVF_XYZRHW的区别
D3DFVF_XYZ和D3DFVF_XYZRHW的区别是:1.D3DXYZ默认的坐标系统用户区中心是 (0,0) 而rhw的左上角是 (0,0)2.D3DXYZ默认的非光照的,而RHW默认就是高洛夫的 ...
- 二十三、Linux任务计划及周期性任务执行:at、crontab命令
一.概述 未来的某时间点执行一次某任务:at, batch周期性运行某任务:crontab 这两个任务的执行结果:会通过邮件发送给用户 (本地终端用户之间的邮件通知) centos 5,6,7默认开启 ...
- COM 基础 之 三大基础接口
摘自 http://blog.csdn.net/liang4/article/details/7530512 1 COM组件实际上是一个C++类,而接口都是纯虚类.组件从接口派生而来. 2 COM组件 ...