您的位置:首页 > 编程语言 > Java开发

JDBC——java连接MySQL封装处理

2019-01-10 20:09 477 查看

MySQL 内  Learn数据库中的 student_info表 中的字段信息为:

 

将字段数据封装,StudentInfo.java

[code]package com.jdbc.model;
/*
* student_info表的实体类
* */
public class StudentInfo {
public StudentInfo() {

}

public StudentInfo(Integer id, String name, String sex, Double score, String birthday) {
this.id = id;
this.name = name;
this.sex = sex;
this.score = score;
this.birthday = birthday;
}

public StudentInfo(String name, String sex, Double score, String birthday) {
this.name = name;
this.sex = sex;
this.score = score;
this.birthday = birthday;
}

private Integer id;
private String name;
private String sex;
private Double score;
private String birthday;

public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Double getScore() {
return score;
}
public void setScore(Double score) {
this.score = score;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}

//重写显示
@Override
public String toString() {
return "StudentInfo [id=" + id + ", name=" + name + ", sex=" + sex + ", score=" + score + ", birthday="
+ birthday + "]";
}

}

将数据库连接方法封装,为静态方法,可直接类名调用。ConnectionDB.java

[code]package com.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class ConnectionDB {
private static String url = "jdbc:mysql://localhost:3306/learn?useUnicode=true&characterEncoding=utf-8";
private static String username = "root";  //MySQL账号
private static String password = "123456";	 //MySQL密码
private static Connection conn;

/**
* 获取数据库连接
* @return
*/
public static Connection getConn() {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}

try {
conn = DriverManager.getConnection(url, username, password);
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}

}

接下来不利用任何框架,封装数据库增删改查方法,并做测试。StudentInfoDao.java

[code]package com.jdbc.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.jdbc.ConnectionDB;
import com.jdbc.model.StudentInfo;

/**
* StudentInfo<->student_info
* O(Object)<->R(Relation)映射    不使用Mybatis,jpa ....框架
*/

public class StudentInfoDao {
/**
*   新增学生
* @param studentInfo
*/
public void add(StudentInfo studentInfo) {
// 连接数据库
Connection conn = ConnectionDB.getConn();

String sql = "insert into student_info(name,sex,birthday,score) values(?,?,?,?)";
try {
// 绑定
PreparedStatement pst = conn.prepareStatement(sql);

// 通过对象往数据库中add数据
// 几个问号几句 (从1开始)
pst.setString(1, studentInfo.getName());
pst.setString(2, studentInfo.getSex());
pst.setString(3, studentInfo.getBirthday());
pst.setDouble(4, studentInfo.getScore());

pst.executeUpdate();

// 关闭数据库
pst.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}

/**
* 根据主键删除相应数据库中的数据
* @param id
*/
public void delById(Integer id) {
// 连接数据库
Connection conn = ConnectionDB.getConn();

String sql = "delete from student_info where id=?";
try {
// 绑定
PreparedStatement pst = conn.prepareStatement(sql);

// 几个问号几句(从1开始)
pst.setInt(1, id);

pst.executeUpdate();

// 关闭数据库
pst.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}

}

/**
* 根据主键加载学生
* @param id
* @return
*/
public StudentInfo selById(Integer id) {
// 连接数据库
Connection conn = ConnectionDB.getConn();

// 将查询得的数据存储进对象中,关系到对象的映射
StudentInfo studentInfo = new StudentInfo();

String sql = "select id,name,sex,birthday,score from student_info where id=?";
try {
// 绑定
PreparedStatement pst = conn.prepareStatement(sql);

// 几个问号几句(从1开始)
pst.setInt(1, id);

ResultSet rs = pst.executeQuery(); //rs为查询指针,初始指向要查询对象的前一个位置
if(rs.next()) {

//将查询结果存进对象
studentInfo.setId(rs.getInt("id"));
studentInfo.setName(rs.getString("name"));
studentInfo.setSex(rs.getString("sex"));
studentInfo.setBirthday(rs.getString("birthday"));
studentInfo.setScore(rs.getDouble("score"));
}

// 关闭数据库
pst.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}

return studentInfo;
}

/**
* 修改学生
* @param studentInfo
*/
public void update(StudentInfo studentInfo) {
// 连接数据库
Connection conn = ConnectionDB.getConn();

String sql = "update student_info set name=?,sex=?,birthday=?,score=? where id=?";
try {
// 绑定
PreparedStatement pst = conn.prepareStatement(sql);

// 不修改的保持原数据
// 几个问号几句(从1开始)
pst.setString(1, studentInfo.getName());
pst.setString(2, studentInfo.getSex());
pst.setString(3, studentInfo.getBirthday());
pst.setDouble(4, studentInfo.getScore());
pst.setInt(5, studentInfo.getId());

pst.executeUpdate();

// 关闭数据库
pst.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}

/**
* 查询所有学生, 所有则通过list返回全部学生
* @return
*/
public List<StudentInfo> selAll(){
// 连接数据库
Connection conn = ConnectionDB.getConn();

// 新建list列表存对象
List<StudentInfo> list = new ArrayList<>();

String sql = "select id,name,sex,birthday,score from student_info";

PreparedStatement pst;

try {
// 绑定
pst = conn.prepareStatement(sql);

ResultSet rs = pst.executeQuery(); //rs指针指向要查询的对象的前一个位置
while(rs.next()) {
// 新建对象
StudentInfo studentInfo = new StudentInfo();

studentInfo.setId(rs.getInt("id"));
studentInfo.setName(rs.getString("name"));
studentInfo.setSex(rs.getString("sex"));
studentInfo.setBirthday(rs.getString("birthday"));
studentInfo.setScore(rs.getDouble("score"));

// 添加进list
list.add(studentInfo);
}
// 关闭数据库
pst.close();
conn.close();

} catch (SQLException e) {
e.printStackTrace();
}

return list;
}

//调用测试
public static void main(String[] args) {
// 日期转字符串
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String nowDate = sdf.format(date);

StudentInfo si = new StudentInfo("Lily","1",100.0,nowDate);

//new 工具对象
StudentInfoDao studentDao = new StudentInfoDao();

// 直接调用内部方法
studentDao.add(si);  // 添加
studentDao.delById(4); // 删除

si = studentDao.selById(17); // 查询

System.out.println("update 前 " + si); //调用内部的toString方法,输出查询到的数据

si.setName("Jim");
si.setSex("0");
studentDao.update(si); // 对上面查询到的数据重新设置值

si = studentDao.selById(17);
System.out.println("update 后 " + si);

List<StudentInfo> list = studentDao.selAll(); // 查询全部

// 范型输出查询到的列表
System.out.println("输出全部列表:");
for(StudentInfo item:list) {
System.out.println(item);
}
}
}

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: