import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties; import org.apache.commons.dbcp.BasicDataSource; public class DBUtils {
private static BasicDataSource dateSource;
static {
//创建属性对象
Properties prop = new Properties();
//得到文件的输入流
InputStream ips = DBUtils2.class.getClassLoader().getResourceAsStream("jdbc.properties");
//把文件加载到属性对象中
try {
prop.load(ips);
//读取数据
String driver = prop.getProperty("driver");
String url = prop.getProperty("url");
String username = prop.getProperty("username");
String password = prop.getProperty("password");
//创建数据源对象
dateSource = new BasicDataSource();
//设置数据库链接信息
dateSource.setDriverClassName(driver);
dateSource.setUrl(url);
dateSource.setUsername(username);
dateSource.setPassword(password);
//设置连接池参数
dateSource.setInitialSize(3);//初始连接数量
dateSource.setMaxActive(5);//最大连接数量 } catch (IOException e) {
e.printStackTrace();
} }
//1、获取链接
public static Connection getConn() throws Exception { //获取连接池中的连接
Connection conn = dateSource.getConnection();
return conn;
}
//2、关闭资源
public static void close(ResultSet rs,Statement stat,Connection conn) {
try {
if (rs!=null) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (stat!=null) {
stat.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
//关闭连接
try {
if (conn!=null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}

DAO

 /**
* 依据用户名查询对应的用户信息。 如果找不到,返回null。
*
* @throws SQLException
*/
public User find(String uname) throws SQLException {
User user = null; Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null; try {
conn = DBUtils.getconn();
String sql = "SELECT * FROM t_user " + "WHERE username=?";
ps = conn.prepareStatement(sql);
ps.setString(1, uname);
rs = ps.executeQuery(); if (rs.next()) {
int id = rs.getInt("id");
String pwd = rs.getString("password");
String email = rs.getString("email"); user = new User();
user.setId(id);
user.setUname(uname);
user.setPwd(pwd);
user.setEmail(email); } } catch (SQLException e) {
e.printStackTrace();
throw e;
} finally {
DBUtils.close(rs, ps, conn);
} return user;
}
/**
* 删除指定信息
* @param id
* @throws SQLException
*/
public void delete(int id) throws SQLException {
Connection conn = null;
PreparedStatement ps = null; try {
conn = DBUtils.getconn();
String sql = "DELETE FROM t_user " + "WHERE id = ?";
ps = conn.prepareStatement(sql);
ps.setInt(1, id);
ps.executeUpdate(); } catch (SQLException e) {
e.printStackTrace();
throw e;
} finally {
DBUtils.close(null, ps, conn);
}
} /**
* 将用户信息插入到t_user表。
*
* @throws SQLException
*
*/
public void save(User user) throws SQLException {
Connection conn = null;
PreparedStatement ps = null; try {
conn = DBUtils.getconn();
String sql = "INSERT INTO t_user " + "VALUES(null,?,?,?)";
ps = conn.prepareStatement(sql);
ps.setString(1, user.getUname());
ps.setString(2, user.getPwd());
ps.setString(3, user.getEmail());
ps.executeUpdate(); } catch (SQLException e) {
e.printStackTrace();
throw e;
} finally {
DBUtils.close(null, ps, conn);
}
} /**
* 从t_user表中查询出所有用户的信息。 注: 一条记录对应一个User对象(即将记录中的数据 存放到User对象里面)。
*
* @throws SQLException
*/
public List<User> findAll() throws SQLException { List<User> users = new ArrayList<User>(); Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null; try {
conn = DBUtils.getconn();
String sql = "SELECT * FROM t_user";
ps = conn.prepareStatement(sql);
rs = ps.executeQuery(); while (rs.next()) { int id = rs.getInt("id");
String uname = rs.getString("username");
String pwd = rs.getString("password");
String email = rs.getString("email"); User user = new User();
user.setId(id);
user.setUname(uname);
user.setPwd(pwd);
user.setEmail(email); users.add(user); } } catch (SQLException e) {
e.printStackTrace();
throw e;
} finally {
DBUtils.close(rs, ps, conn);
} return users; }

Java中访问数据库的步骤

 //注册驱动
Class.forName("com.mysql.jdbc.Driver");
//建立连接
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db3", "root", "");
System.out.println("创建完毕");
//创建Statement
Statement stat = conn.createStatement();
String sql = "delete from jdbc01 where id=1";
//执行sql语句(若SQL语句为查询语句需要处理结果集)
stat.executeUpdate(sql);
System.out.println("删除完毕");
//关闭连接
stat.close();
conn.close();

数据库的基本连接

 public static void main(String[] args) throws Exception {
//创建数据源对象
BasicDataSource dateSource = new BasicDataSource();
//设置数据库连接信息
dateSource.setDriverClassName("com.mysql.jdbc.Driver");
dateSource.setUrl("jdbc:mysql://localhost:3306/db3");
dateSource.setUsername("root");
dateSource.setPassword("root");
//设置连接池参数
dateSource.setInitialSize(3);//初始连接数量
dateSource.setMaxActive(5);//最大连接数量
//获取连接池中的连接
Connection conn = dateSource.getConnection();
System.out.println(conn);
}

JDBC示例程序的更多相关文章

  1. 通过Jexus 部署 dotnetcore版本MusicStore 示例程序

    ASPNET Music Store application 是一个展示最新的.NET 平台(包括.NET Core/Mono等)上使用MVC 和Entity Framework的示例程序,本文将展示 ...

  2. .NET跨平台:在Ubuntu上用自己编译的dnx运行ASP.NET 5示例程序

    在 Linux Ubuntu 上成功编译 dnx 之后,会在 artifacts/build/ 文件夹中生成 dnx-coreclr-linux-x64/ 与 dnx-mono/ 这2个文件夹,前者是 ...

  3. .NET跨平台:在CentOS上编译dnx并运行ASP.NET 5示例程序

    在之前的博文中我们在 Ubuntu 上成功编译出了 dnx ,并且用它成功运行了 ASP.NET 5 示例程序.在这篇博文中我们将 Ubuntu 换成 CentOS. 目前 dnx 的编译需要用到 m ...

  4. Salesforce Apex 使用JSON数据的示例程序

    本文介绍了一个在Salesforce Apex中使用JSON数据的示例程序, 该示例程序由以下几部分组成: 1) Album.cls, 定了了封装相关字段的数据Model类 2) RestClient ...

  5. osg 示例程序解析之osgdelaunay

    osg 示例程序解析之osgdelaunay 转自:http://lzchenheng.blog.163.com/blog/static/838335362010821103038928/ 本示例程序 ...

  6. DotNetBar for Windows Forms 12.7.0.10_冰河之刃重打包版原创发布-带官方示例程序版

    关于 DotNetBar for Windows Forms 12.7.0.10_冰河之刃重打包版 --------------------11.8.0.8_冰河之刃重打包版------------- ...

  7. DotNetBar for Windows Forms 12.5.0.2_冰河之刃重打包版原创发布-带官方示例程序版

    关于 DotNetBar for Windows Forms 12.5.0.2_冰河之刃重打包版 --------------------11.8.0.8_冰河之刃重打包版-------------- ...

  8. DotNetBar for Windows Forms 12.2.0.7_冰河之刃重打包版原创发布-带官方示例程序版

    关于 DotNetBar for Windows Forms 12.2.0.7_冰河之刃重打包版 --------------------11.8.0.8_冰河之刃重打包版-------------- ...

  9. ACEXML解析XML文件——简单示例程序

    掌握了ACMXML库解析XML文件的方法后,下面来实现一个比较完整的程序. 定义基本结构 xml文件格式如下 <?xml version="1.0"?> <roo ...

随机推荐

  1. 为程序设置多语言界面——C#

    考虑到程序的国际化需求,需要为程序设置多语言界面. 1,新建一个资源文件,名字可以是对应界面+语言代码(MainForm.zh-CN).这样资源文件就会自动添加到对应界面下面. 2,更改界面属性Loc ...

  2. form编码方式application/x-www-form-urlencoded和multipart/form-data的区别

    form元素有个enctype属性,可以指定数据编码方式,有如下三种: 1. application/x-www-form-urlencoded: 表单数据编码为键值对,&分隔 2. mult ...

  3. Debian中配置静态IP

    默认安装Debian的时候是用dhcp服务的,有时我们需要设置一下静态IP. 一共涉及两个文件的修改 /etc/network/interfaces auto eth0#iface eth0 inet ...

  4. Reids学习1 -- 初识Redis

    1. Reids和其他类型数据库对比 名称 类型 数据库存储选项 查询类型 附加功能 Redis 使用内存存储的非关系数据库 字符串,列表,集和,散列表,有序集合 每个类型有自己的专属命令,还有批量操 ...

  5. Redis安装和实际应用

    上次介绍了Redis的来龙去脉以及相关一些情况,点击回顾<深入浅出Redis>,接下来我们再讲讲Redis的安装和实际应用. 一.Redis的安装 下载安装包,redis-3.2.9.ta ...

  6. FastDFS客户端与自定义文件存储系统

    <1>安装 安装提供给大家的fdfs_client-py-master.zip到虚拟环境中 pip install fdfs_client-py-master.zip pip instal ...

  7. FTP服务器搭建

    FTP 服务器架设: 关闭防火墙 service iptables stop 关闭SELinux setenforce 0 安装所需依赖及编译工具 yum install -y gcc openssl ...

  8. Kali学习笔记40:SQL手工注入(2)

    上一篇讲到可以通过注入得到数据库中所有的表信息 而SQL注入能不能做数据库之外的事情呢? 读取文件: ' union select null,load_file('/etc/passwd') -- 为 ...

  9. redis安装以及安全配置

    redis安装以及安全配置 1. 安装 sudo apt-get install redis-server 使用which查询redis执行体安装路径: which redis-server #/us ...

  10. 签名时出错: 未在路径 C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\bin

    在运行winform程序时,由于清理解决方案等缘故,出现了下面的情况 解决办法:项目-属性-签名-取消勾选“为ClickOne清单签名” 问题完美解决