- Java数据库连接,(Java Database Connectivity,简称JDBC)是Java语言中用来规范客户端程序如何来访问数据库的应用程序接口,提供了诸如查询和更新数据库中数据的方法。我们通常说的JDBC是面向关系型数据库的。
- Java利用jdbc连接数据库需要用到
mysql-connector-java
的jar包,根据数据库版本选择不同版本的jar包,我的数据库是MySQL5.7的,所以我选用的是mysql-connector-java-5.1.41-bin.jar
// 这里调用了自己封装好的方法,后面具体代码会给出
Connection conn = DBUtil.connect(); // 数据库连接
PreparedStatement pst = null; // SQL预编译器
ResultSet rs = null; // 查询结果集(只有查询语句会用到)
// 编写SQL,?为占位符
String sql = "SELECT * FROM `user` WHERE `username`=? AND `password`=?";
// 预编译SQL
pst = conn.prepareStatement(sql);
// 配置对应字段占位符的值
pst.setString(1, username);
pst.setString(2, password);
// 执行SQL查询语句,返回结果集
rs = pst.executeQuery();
// 关闭流
// 这里调用了自己封装好的方法,后面具体代码会给出
DBUtil.closeStream(rs);
DBUtil.closeStream(pst);
DBUtil.closeStream(conn);
db.properties
# jdbc mysql url
url=jdbc:mysql://127.0.0.1:3306/wzry?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useSSL=false
# db username
username=root
# db password
password=your db password
# db driver
driver=com.mysql.jdbc.Driver
package com.feonix.jdbc.util;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
public class DBUtil {
/** 数据库jdbc连接地址 */
private static String url;
/** 数据库用户名 */
private static String username;
/** 数据库密码 */
private static String password;
/** 数据库驱动类 */
private static String driver;
// 实例化properties对象
static Properties prop = new Properties();
static {
try {
// 加载配置文件
prop.load(new FileInputStream("resources/db.properties"));
// 获取url
url = prop.getProperty("url");
// 获取username
username = prop.getProperty("username");
// 获取password
password = prop.getProperty("password");
// 获取driver
driver = prop.getProperty("driver");
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 获取数据库连接
*
* @return
*/
public static Connection connect() {
try {
// 1.加载安装驱动(利用反射)
Class.forName(driver);
// 2.获取数据库的连接(使用驱动管理DriverManager)
return DriverManager.getConnection(url, username, password);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 关闭数据库流
*
* @param stream
*/
public static void closeStream(Object stream) {
if (stream != null) {
try {
if (stream instanceof Connection) {
((Connection) stream).close();
}
if (stream instanceof PreparedStatement) {
((PreparedStatement) stream).close();
}
if (stream instanceof ResultSet) {
((ResultSet) stream).close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
package com.feonix.jdbc.entity;
public class User {
/** 主键 用户id */
private Integer id;
/** 用户名 */
private String username;
/** 密码 */
private String password;
/** 余额 */
private Double money;
public User() {
super();
}
public User(Integer id, String username, String password, Double money) {
super();
this.id = id;
this.username = username;
this.password = password;
this.money = money;
}
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;
}
public Double getMoney() {
return money;
}
public void setMoney(Double money) {
this.money = money;
}
}
package com.feonix.jdbc.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.feonix.jdbc.entity.User;
import com.feonix.jdbc.util.DBUtil;
public class UserDao {
/**
* 根据用户名和密码查询用户
*
* @param username
* @param password
* @return
*/
public User findUser(String username, String password) {
User user = null;
// 获取连接
Connection conn = DBUtil.connect();
PreparedStatement pst = null;
ResultSet rs = null;
// 编写SQL,?为占位符
String sql = "SELECT * FROM `user` WHERE `username`=? AND `password`=?";
try {
// 预编译SQL
pst = conn.prepareStatement(sql);
// 配置对应字段占位符的值
pst.setString(1, username);
pst.setString(2, password);
// 执行SQL查询语句,返回结果集
rs = pst.executeQuery();
while (rs.next()) {
user = new User();
user.setId(rs.getInt("id"));
user.setUsername(rs.getString("username"));
user.setPassword(rs.getString("password"));
user.setMoney(rs.getDouble("money"));
}
return user;
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 关闭流
DBUtil.closeStream(rs);
DBUtil.closeStream(pst);
DBUtil.closeStream(conn);
}
return null;
}
/**
* 添加用户
*
* @param username
* @param password
* @return
*/
public Integer addUser(String username, String password) {
// 获取连接
Connection conn = DBUtil.connect();
PreparedStatement pst = null;
// 编写SQL
String sql = "INSERT INTO `user` (`username`,`password`) VALUES(?,?);";
try {
// 预编译SQL
pst = conn.prepareStatement(sql);
// 配置对应字段占位符的值
pst.setString(1, username);
pst.setString(2, password);
// 执行SQL插入语句,返回受影响条数
return pst.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 关闭流
DBUtil.closeStream(pst);
DBUtil.closeStream(conn);
}
return 0;
}
/**
* 修改密码
*
* @param id
* @param password
* @return
*/
public Integer updatePasswd(Integer id, String password) {
// 获取连接
Connection conn = DBUtil.connect();
PreparedStatement pst = null;
// 编写SQL
String sql = "UPDATE `user` SET `password`=? WHERE `id`=?";
try {
// 预编译SQL
pst = conn.prepareStatement(sql);
// 配置对应字段占位符的值
pst.setString(1, password);
pst.setInt(2, id);
// 执行SQL插入语句,返回受影响条数
return pst.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 关闭流
DBUtil.closeStream(pst);
DBUtil.closeStream(conn);
}
return 0;
}
/**
* 充值余额
*
* @param id
* @param money
* @return
*/
public Integer updateMoney(Integer id, Double money) {
// 获取连接
Connection conn = DBUtil.connect();
PreparedStatement pst = null;
// 编写SQL
String sql = "UPDATE `user` SET `money`=`money`+? WHERE `id`=?";
try {
// 预编译SQL
pst = conn.prepareStatement(sql);
// 配置对应字段占位符的值
pst.setDouble(1, money);
pst.setInt(2, id);
// 执行SQL插入语句,返回受影响条数
return pst.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 关闭流
DBUtil.closeStream(pst);
DBUtil.closeStream(conn);
}
return 0;
}
}
package com.feonix.jdbc.controller;
import java.util.Scanner;
import com.feonix.jdbc.dao.UserDao;
import com.feonix.jdbc.entity.User;
public class UserController {
static Scanner scanner = new Scanner(System.in);
static boolean isLogin = false;
static User loginUser = null;
public static void main(String[] args) {
boolean flag = true;
while (flag) {
System.out.println("欢迎来到王者荣耀商店");
System.out.println((!isLogin ? "输入1登录;输入2注册" : "输入3充值;输入4修改密码;输入5退出登录") + ";输入0退出商店");
int command = scanner.nextInt();
switch (command) {
case 1:
login();
break;
case 2:
regist();
break;
case 3:
recharge();
break;
case 4:
modifyPasswd();
break;
case 5:
isLogin = false;
loginUser = null;
break;
case 0:
flag = false;
break;
default:
System.out.println("无效的指令,请重新输入");
}
}
scanner.close();
}
/**
* 登录
*/
public static void login() {
System.out.print("用户名:");
String username = scanner.next();
System.out.print("密码:");
String password = scanner.next();
UserDao dao = new UserDao();
User user = dao.findUser(username, password);
if (user == null) {
System.out.println("您输入的账号或密码不正确");
} else {
System.out.println("登录成功");
isLogin = true;
loginUser = user;
}
}
/**
* 注册
*/
public static void regist() {
String command = null;
ext: while (true) {
System.out.println("请输入用户名(限制20个字符以内):");
String username = scanner.next();
System.out.println("请输入密码(6~20个字符):");
String password = scanner.next();
System.out.println("请再次输入密码:");
String repassword = scanner.next();
while (true) {
System.out.println("输入1确认注册;输入2重新输入;输入3退出注册");
command = scanner.next();
if ("1".equals(command)) {
if (username.trim().isEmpty()) {
System.out.println("用户名不能为空");
break;
}
if (username.trim().length() > 20) {
System.out.println("用户名不能超过20个字符");
break;
}
if (password.trim().isEmpty()) {
System.out.println("密码不能为空");
break;
}
if (password.trim().length() < 6 || password.trim().length() > 20) {
System.out.println("密码必须是6~20个字符");
break;
}
if (!password.trim().equals(repassword.trim())) {
System.out.println("两次输入的密码不一致");
break;
}
UserDao dao = new UserDao();
User user = dao.findUser(username, password);
if (user != null) {
System.out.println("用户已存在,不能重复注册");
break;
}
int rs = dao.addUser(username, password);
if (rs > 0) {
System.out.println("注册成功");
break ext;
} else {
System.out.println("注册失败");
break;
}
} else if ("2".equals(command)) {
break;
} else if ("3".equals(command)) {
break ext;
} else {
System.out.println("无效的指令,请重新输入");
}
}
}
}
/**
* 修改密码
*/
public static void modifyPasswd() {
ext1: while (true) {
System.out.println("请输入原密码");
String oldpassword = scanner.next();
if (!loginUser.getPassword().equals(oldpassword)) {
System.out.println("原密码输入错误,请确认后重新输入");
continue;
}
System.out.println("请输入新密码(6~20个字符)");
String password = scanner.next();
System.out.println("请再次输入密码:");
String repassword = scanner.next();
ext2: while (true) {
System.out.println("输入1确认修改;输入2重新输入;输入3退出");
int command = scanner.nextInt();
switch (command) {
case 1:
if (password.trim().isEmpty()) {
System.out.println("密码不能为空");
break;
}
if (password.trim().length() < 6 || password.trim().length() > 20) {
System.out.println("密码必须是6~20个字符");
break;
}
if (!password.trim().equals(repassword.trim())) {
System.out.println("两次输入的密码不一致");
break;
}
UserDao dao = new UserDao();
int rs = dao.updatePasswd(loginUser.getId(), password);
if (rs > 0) {
System.out.println("密码修改成功");
isLogin = false;
loginUser = null;
break ext1;
} else {
System.out.println("密码修改失败,请重试");
break ext2;
}
case 2:
break ext2;
case 3:
break ext1;
default:
System.out.println("无效的指令,请重新输入");
}
}
}
}
/**
* 充值
*/
public static void recharge() {
while (true) {
System.out.println("欢迎来到荣耀商店充值系统");
System.out.println("请选择要充值的额度(1:1000;2:2000;3:3000;4:4000;5:5000;6:6000;7:自定义;0:退出充值)");
int type = scanner.nextInt();
int money = 0;
if (type == 7) {
System.out.println("请输入充值额度");
money = scanner.nextInt();
} else if (type >= 1 && type <= 6) {
money = type * 1000;
} else if (type == 0) {
break;
} else {
System.out.println("无效的指令,请重新输入");
}
if (money > 0) {
UserDao dao = new UserDao();
int rs = dao.updateMoney(loginUser.getId(), (double) money);
if (rs > 0) {
System.out.println("充值成功");
} else {
System.out.println("充值失败");
}
}
}
}
}