javaWeb_JDBC_面向对象编程在JDBC中的使用


jdbc中加入对象操作


1.改变
之前的操作都是使用sql语句对数据库中的表的字段进行一个操作,那个这一个改变的是对一个字段值的操作。那么我们在实际的开发中,使用的
是对对象的操作,也就是一条记录就是一个对象,字段就是这一个对象的对应属性,那么我们操作这一个对象的时候实际操作的是这一个数据库
中的记录。


2.操作步骤
(1).创建对象
创建的对象其实就是和数据库表中的字段一一对应。

(2).创建数据库表
根据实体对象(也即是学生对象)编写数据库表以及对应的字段。[实体对象与数据库表之间的对应关系]

(3).创建数据库操作的工具类

(4).实体操作类
实现对数据库操作的增删改查

(5).编写测试类


3.代码测试--实现学生对象的增删查改[仅示例,代码不可使用]

(1).注意事项1:
要能够使用基本的sql语句实现基本的增删改查(能够在navicat上使用)

(2).代码实现
//创建学生对象
public class Student {
//id
private int id;
//姓名
private String studentName;
//年龄
private int age;
//籍贯
private String nativePlace;

//无参
public Student(){}

//带参
public Student(int id,String studentName,int age,String nativePalace){
this.id = id;
this.studentName = studentName;
this.age = age;
this.nativePlace = nativePalace;
}

@Override
public String toString() {
return "Student [id=" + id + ", studentName=" + studentName + ", age="
+ age + ", nativePlace=" + nativePlace + "]";
}

//省略getXxx()和setXxx()方法
}

//封装了增删改和数据库连接以及释放资源的工具类

public class JDBCTools {

/**
* 执行 SQL 的方法
*
* @param sql: insert, update 或 delete。 而不包含 select
*/
public static void update(String sql) {
Connection connection = null;
Statement statement = null;

try {
// 1. 获取数据库连接
connection = getConnection();

// 2. 调用 Connection 对象的 createStatement() 方法获取 Statement 对象
statement = connection.createStatement();

// 4. 发送 SQL 语句: 调用 Statement 对象的 executeUpdate(sql) 方法
statement.executeUpdate(sql);

} catch (Exception e) {
e.printStackTrace();
} finally {
// 5. 关闭数据库资源: 由里向外关闭.
releaseDB(null, statement, connection);
}
}

/**
* 释放数据库资源的方法
*
* @param resultSet
* @param statement
* @param connection
*/
public static void releaseDB(ResultSet resultSet, Statement statement,
Connection connection) {

if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}

if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}

if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}

}

/**
* 获取数据库连接的方法
*
*/
public static Connection getConnection() throws IOException,
ClassNotFoundException, SQLException {
// 0. 读取 jdbc.properties
/**
* 1). 属性文件对应 Java 中的 Properties 类 2). 可以使用类加载器加载 bin 目录(类路径下)的文件
*/
Properties properties = new Properties();
InputStream inStream = ReflectionUtils.class.getClassLoader()
.getResourceAsStream("jdbc.properties");
properties.load(inStream);

// 1. 准备获取连接的 4 个字符串: user, password, jdbcUrl, driverClass
String user = properties.getProperty("user");
String password = properties.getProperty("password");
String jdbcUrl = properties.getProperty("jdbcUrl");
String driverClass = properties.getProperty("driverClass");

// 2. 加载驱动: Class.forName(driverClass)
Class.forName(driverClass);

// 3. 调用
// DriverManager.getConnection(jdbcUrl, user, password)
// 获取数据库连接
Connection connection = DriverManager.getConnection(jdbcUrl, user,password);
return connection;
}
}

//测试类
public class JDBCTest {

public static void main(String[] args) {
Student student = new Student();
student.setStudentName("张三");
student.setAge(12);
student.setNativePlace("唐朝");
//------------------
Student student1 = new Student();
student1.setStudentName("李四");
student1.setAge(15);
student1.setNativePlace("宋朝");

//添加
//JDBCTest.addNewStudent(student1);
//删
//JDBCTest.deleteStudent(student);
//改
//JDBCTest.updateStudent(student1);
//查
Student queryStudent = JDBCTest.searchStudent();
System.out.println("查询结果是:"+queryStudent);
}



public static Student searchStudent() {
//先定义一个基本sql
String sql = "SELECT * FROM student WHERE ";

@SuppressWarnings("resource")
Scanner scanner = new Scanner(System.in);

System.out.print("请输入查询名字:");
String getName = scanner.next();
sql = sql + "studentName = '" + getName + "'";

System.out.println(sql);
Student student = getStudent(sql);

return student;
}

/**
* 根据传入的 SQL 返回 Student 对象
* @param sql
* @return
*/
public static Student getStudent(String sql) {

Student stu = null;

Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;

try {
connection = JDBCTools.getConnection();
statement = connection.createStatement();
resultSet = statement.executeQuery(sql);

if (resultSet.next()) {
stu = new Student(resultSet.getInt(1), resultSet.getString(2),
resultSet.getInt(3), resultSet.getString(4));
}

} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCTools.releaseDB(resultSet, statement, connection);
}

return stu;
}

public static void updateStudent(Student st){
String sql = "Update student set studentName='"
+ st.getStudentName() +"',age= "
+ st.getAge() + ",nativePlace='"
+ st.getNativePlace() +"'where studentName='"
+ st.getStudentName() + "'";
System.out.println(sql);
JDBCTools.update(sql);
}

public static void deleteStudent(Student st){
String sql = "delete from student where studentName='"
+st.getStudentName()+"'";
System.out.println(sql);
JDBCTools.update(sql);
}

public static void addNewStudent(Student student) {
// 1. 准备一条 SQL 语句:
String sql = "INSERT INTO student VALUES("
+ student.getId()
+ ",'" + student.getStudentName()
+ "'," + student.getAge() + ",'"
+ student.getNativePlace()+"'"
+ ")";

System.out.println(sql);

JDBCTools.update(sql);
}

}

//反射类
/**
* 反射的 Utils 函数集合
* 提供访问私有变量, 获取泛型类型 Class, 提取集合中元素属性等 Utils 函数
* @author Administrator
*
*/
public class ReflectionUtils {


/**
* 通过反射, 获得定义 Class 时声明的父类的泛型参数的类型
* 如: public EmployeeDao extends BaseDao<Employee, String>
* @param clazz
* @param index
* @return
*/
public static Class<?> getSuperClassGenricType(Class<?> clazz, int index){
Type genType = clazz.getGenericSuperclass();

if(!(genType instanceof ParameterizedType)){
return Object.class;
}

Type [] params = ((ParameterizedType)genType).getActualTypeArguments();

if(index >= params.length || index < 0){
return Object.class;
}

if(!(params[index] instanceof Class)){
return Object.class;
}

return (Class<?>) params[index];
}

/**
* 通过反射, 获得 Class 定义中声明的父类的泛型参数类型
* 如: public EmployeeDao extends BaseDao<Employee, String>
* @param <T>
* @param clazz
* @return
*/
@SuppressWarnings("unchecked")
public static<T> Class<T> getSuperGenericType(Class<?> clazz){
return (Class<T>) getSuperClassGenricType(clazz, 0);
}

/**
* 循环向上转型, 获取对象的 DeclaredMethod
* @param object
* @param methodName
* @param parameterTypes
* @return
*/
public static Method getDeclaredMethod(Object object, String methodName, Class<?>[] parameterTypes){

for(Class<?> superClass = object.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()){
try {
//superClass.getMethod(methodName, parameterTypes);
return superClass.getDeclaredMethod(methodName, parameterTypes);
} catch (NoSuchMethodException e) {
//Method 不在当前类定义, 继续向上转型
}
//..
}

return null;
}

/**
* 使 filed 变为可访问
* @param field
*/
public static void makeAccessible(Field field){
if(!Modifier.isPublic(field.getModifiers())){
field.setAccessible(true);
}
}

/**
* 循环向上转型, 获取对象的 DeclaredField
* @param object
* @param filedName
* @return
*/
public static Field getDeclaredField(Object object, String filedName){

for(Class<?> superClass = object.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()){
try {
return superClass.getDeclaredField(filedName);
} catch (NoSuchFieldException e) {
//Field 不在当前类定义, 继续向上转型
}
}
return null;
}

/**
* 直接调用对象方法, 而忽略修饰符(private, protected)
* @param object
* @param methodName
* @param parameterTypes
* @param parameters
* @return
* @throws InvocationTargetException
* @throws IllegalArgumentException
*/
public static Object invokeMethod(Object object, String methodName, Class<?> [] parameterTypes,
Object [] parameters) throws InvocationTargetException{

Method method = getDeclaredMethod(object, methodName, parameterTypes);

if(method == null){
throw new IllegalArgumentException("Could not find method [" + methodName + "] on target [" + object + "]");
}

method.setAccessible(true);

try {
return method.invoke(object, parameters);
} catch(IllegalAccessException e) {
System.out.println("不可能抛出的异常");
}

return null;
}

/**
* 直接设置对象属性值, 忽略 private/protected 修饰符, 也不经过 setter
* @param object
* @param fieldName
* @param value
*/
public static void setFieldValue(Object object, String fieldName, Object value){
Field field = getDeclaredField(object, fieldName);

if (field == null)
throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + object + "]");

makeAccessible(field);

try {
field.set(object, value);
} catch (IllegalAccessException e) {
System.out.println("不可能抛出的异常");
}
}

/**
* 直接读取对象的属性值, 忽略 private/protected 修饰符, 也不经过 getter
* @param object
* @param fieldName
* @return
*/
public static Object getFieldValue(Object object, String fieldName){
Field field = getDeclaredField(object, fieldName);

if (field == null)
throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + object + "]");

makeAccessible(field);

Object result = null;

try {
result = field.get(object);
} catch (IllegalAccessException e) {
System.out.println("不可能抛出的异常");
}

return result;
}
}

猜你喜欢

转载自www.cnblogs.com/nwxayyf/p/10350603.html