1.jdbc是什么
- JDBC(Java DataBase Connectivity,java数据库连接)是一种用于执行SQL语句的Java API,可以为多种关系数据库提供统一访问,它由一组用Java语言编写的类和接口组成。JDBC提供了一种基准,据此可以构建更高级的工具和接口,使数据库开发人员能够编写数据库应用程序。(百度百科)
- jdbc经常用来连接数据库,创建sql或者mysql语句,使用相关的api去执行sql语句,从而操作数据库,达到查看或者修改数据库的目的。
- 学习jbbc要求对java编程有一定了解,并了解一种数据库系统以及sql语句。
- 环境要求:
1.本地装好jdk,并且装好mysql数据库,我是直接装过wamp带有mysql数据库
2.使用eclipse开发
2.使用eclipse开发
2.1 创建数据库,数据表
数据库名字是test,数据表的名字是student,里面有四个字段,一个是id,也就是主键(自动递增),还有名字,年龄,成绩。最后先使用sql语句插入六个测试记录。
CREATE DATABASE `test` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci; CREATE TABLE `student` ( `id` INT NOT NULL AUTO_INCREMENT , `name` VARCHAR(20) NOT NULL , `age` INT NOT NULL , `score` DOUBLE NOT NULL , PRIMARY KEY (`id`)) ENGINE = MyISAM; INSERT INTO `student` VALUES (1, '小红', 26, 83); INSERT INTO `student` VALUES (2, '小白', 23, 93); INSERT INTO `student` VALUES (3, '小明', 34, 45); INSERT INTO `student` VALUES (4, '张三', 12, 78); INSERT INTO `student` VALUES (5, '李四', 33, 96); INSERT INTO `student` VALUES (6, '魏红', 23, 46);
2.2 使用eclipse创建项目
打开eclipse–> File --> new -->Project ,创建java项目
输入项目的名字,然后点击Finish
代码的结构如下(一共创建了四个包,action是业务层,这里暂时写得与Test测试一样,去调用dao的方法,dao包下面是操作数据表的dao类,db包下面是封装好的db数据库连接工具类,model是与数据库表对应的model类,也就是模型层):
Student.class
package model;/** * student类,字段包括id,name,age,score * 实现无参构造,带参构造,toString方法,以及get,set方法 * @author 秦怀 */public class Student { private int id; private String name; private int age; private double score; public Student() { super(); // TODO Auto-generated constructor stub } public Student(String name, int age, double score) { super(); = name; this.age = age; this.score = score; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public double getScore() { return score; } public void setScore(double score) { this.score = score; } @Override public String toString() { return "Student [id=" + id + ", name=" + name + ", age=" + age + ", score=" + score + "]"; } }
DBUtil.class
package db;import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;/** * 工具类,获取数据库的连接 * @author 秦怀 * */public class DBUtil { private static String URL="jdbc:mysql://127.0.0.1:3306/test"; private static String USER="root"; private static String PASSWROD ="123456"; private static Connection connection=null; static{ try { Class.forName("com.mysql.jdbc.Driver"); // 获取数据库连接 connection=DriverManager.getConnection(URL,USER,PASSWROD); System.out.println("连接成功"); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // 返回数据库连接 public static Connection getConnection(){ return connection; }}
StudentDao.class
package dao;import model.Student;import java.util.ArrayList;import java.util.List;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import db.DBUtil;/** * 操作学生表的dao类 * @author 秦怀 * 下面均使用预编译的方法 */public class StudentDao { //将连接定义为单例 private static Connection connection = DBUtil.getConnection(); // 添加新的学生 public void addStudent(Student student){ String sql ="insert into student(name,age,score) "+ "values(?,?,?)"; boolean result = false; try { // 将sql传进去预编译 PreparedStatement preparedstatement = connection.prepareStatement(sql); // 下面把参数传进去 preparedstatement.setString(1, student.getName()); preparedstatement.setInt(2, student.getAge()); preparedstatement.setDouble(3, student.getScore()); preparedstatement.execute(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println("创建数据库连接失败"); } } // 更新学生信息 public void updateStudent(Student student){ String sql = "update student set name = ? ,age =?,score = ? where id = ? "; boolean result = false; try { PreparedStatement preparedStatement = connection.prepareStatement(sql); preparedStatement.setString(1, student.getName()); preparedStatement.setInt(2, student.getAge()); preparedStatement.setDouble(3, student.getScore()); preparedStatement.setInt(4, student.getId()); preparedStatement.executeUpdate(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println("连接数据库失败"); } } // 根据id删除一个学生 public void deleteStudent(int id){ String sql = "delete from student where id = ?"; boolean result = false; try { PreparedStatement preparedStatement = connection.prepareStatement(sql); preparedStatement.setInt(1, id); result=preparedStatement.execute(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // 根据id查询学生 public Student selectStudent(int id){ String sql ="select * from student where id =?"; try { PreparedStatement preparedStatement = connection.prepareStatement(sql); preparedStatement.setInt(1, id); ResultSet resultSet = preparedStatement.executeQuery(); Student student = new Student(); // 一条也只能使用resultset来接收 while(resultSet.next()){ student.setId(resultSet.getInt("id")); student.setName(resultSet.getString("name")); student.setAge(resultSet.getInt("age")); student.setScore(resultSet.getDouble("score")); } return student; } catch (SQLException e) { // TODO: handle exception } return null; } // 查询所有学生,返回List public List<Student> selectStudentList(){ List<Student>students = new ArrayList<Student>(); String sql ="select * from student "; try { PreparedStatement preparedStatement = DBUtil.getConnection().prepareStatement(sql); ResultSet resultSet = preparedStatement.executeQuery(); // 不能把student在循环外面创建,要不list里面六个对象都是一样的,都是最后一个的值, // 因为list add进去的都是引用 // Student student = new Student(); while(resultSet.next()){ Student student = new Student(); student.setId(resultSet.getInt(1)); student.setName(resultSet.getString(2)); student.setAge(resultSet.getInt(3)); student.setScore(resultSet.getDouble(4)); students.add(student); } } catch (SQLException e) { // TODO: handle exception } return students; }}
StudentAction.class
package action;import java.util.List;import dao.StudentDao;import model.Student;public class StudentAction { /** * @param args */ public static void main(String[] args) { StudentDao studentDao = new StudentDao(); // TODO Auto-generated method stub System.out.println("========================查询所有学生========================"); List<Student> students =studentDao.selectStudentList(); for(int i=0;i<students.size();i++){ System.out.println(students.get(i).toString()); } System.out.println("========================修改学生信息========================"); Student stu2 = new Student("Jam",20,98.4); stu2.setId(2); studentDao.updateStudent(stu2); System.out.println("========================通过id查询学生========================"); Student student = studentDao.selectStudent(2); System.out.println(student.toString()); System.out.println("========================增加学生========================"); Student stu = new Student("new name",20,98.4); studentDao.addStudent(stu); System.out.println("========================删除学生信息========================"); studentDao.deleteStudent(4); System.out.println("========================查询所有学生========================"); students =studentDao.selectStudentList(); for(int i=0;i<students.size();i++){ System.out.println(students.get(i).toString()); } }}
执行的结果: