JDBC通过对象的方式来获取数据库信息并读取

Java的JDBC理论知识的以及如何使用的详细介绍

JDBC工具类的创建和使用

JDBC学习课堂笔记

在学习本博客内容之前,可以先查看前面三篇博客内容,下面的内容是创建对象之后,通过GetXxx()和SetXxx()方法,来设置数据库的连接信息。

在创建Java项目之前,先建立数据库信息,代码如下:

create table tbStudent(
	id int PRIMARY KEY AUTO_INCREMENT,
	name varchar(20),
	age int,
	classid varchar(10)
);

向数据库中插入数据

insert into tbStudent values(null,"张三",18,"2019");
insert into tbStudent values(null,"李四",19,"2019");
insert into tbStudent values(null,"王五",20,"2018");

在这里插入图片描述

Java项目代码

/**
 * 
 */
package itwcn.com;

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

/**
 * 数据源管理器
 */
public class JdbcDataSource {
    
    
	private String ip = null;   // 数据库服务器所在主机的IP地址
	private String port = null; // 数据库服务器程序的端口号
	private String dbName = null;  // 保存数据库名称
	
	private String id = null;  // 登录数据库服务器的用户账号
	private String password = null;  // 登录密码
	private Connection conn = null;  // 连接对象
		
	public JdbcDataSource() {
    
    
		driverInni();
	}
	
	public JdbcDataSource(String ip, String port, String dbName,
			              String id, String password) {
    
    
		this.setIp(ip);
		this.setPort(port);
		this.setDbName(dbName);
		this.setId(id);
		this.setPassword(password);
		
		driverInni();
	}
	
	/**添加数据库驱动*/
	private boolean driverInni() {
    
    
		boolean bR = false;
		try {
    
    
			Class.forName("com.mysql.cj.jdbc.Driver"); // 使用类名称加载驱动类
			bR = true;
		} catch (ClassNotFoundException e) {
    
    
			e.printStackTrace();
		}
		return bR;
	}
	/**创建连接对象*/
	private boolean createConnection() {
    
    
		boolean bR = false;
		String strUrl = "jdbc:mysql://" + this.ip + ":" + this.port +
				        "/" + this.dbName + "?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=UTF-8";		
		try {
    
    
			this.conn = DriverManager.getConnection(strUrl, this.id, this.password);
			bR = true;
		} catch (SQLException e) {
    
    
			e.printStackTrace();
		}
		return bR;		
	}
	
	/**为用户提供链接对象*/
	public Connection getConnection() {
    
    
		if(this.conn==null) {
    
    
			createConnection();
		}
		return this.conn;
	}
	
	public String getIp() {
    
    
		return ip;
	}

	public void setIp(String ip) throws NullPointerException{
    
    
		if(ip==null||ip.trim().isEmpty()) {
    
    
			throw new NullPointerException("主机IP不能为空");
		}
		this.ip = ip;
	}

	public String getPort() {
    
    
		return port;
	}

	public void setPort(String port) throws NullPointerException{
    
    
		if(port==null||port.trim().isEmpty()) {
    
    
			throw new NullPointerException("服务器端口不能为空");
		}
		this.port = port;
	}

	public String getDbName() {
    
    
		return dbName;
	}

	public void setDbName(String dbName) throws NullPointerException{
    
    
		if(dbName==null||dbName.trim().isEmpty()) {
    
    
			throw new NullPointerException("数据库名称不能为空");
		}
		this.dbName = dbName;
	}

	public String getId() {
    
    
		return id;
	}

	public void setId(String id) throws NullPointerException{
    
    
		if(id==null|| id.trim().isEmpty()) {
    
    
			throw new NullPointerException("用户账号不能为空");
		}
		this.id = id;
	}

	public String getPassword() {
    
    
		return password;
	}

	public void setPassword(String password) {
    
    
		this.password = password;
		System.out.println();
	}
}

下面是测试代码

package itwcn.com;

import java.sql.*;

/**
 * 测试类
 *
 */
public class Test {
    
    

	/**
	 * 测试主方法
	 */
	public static void main(String[] args) {
    
    
		JdbcDataSource jdcA = null;
		Connection cnA = null;				
		jdcA = new JdbcDataSource(); // 使用无参数的构造方法创建数据源对象
		jdcA.setIp("127.0.0.1");
		jdcA.setPort("3306");
		jdcA.setDbName("dbTest");    // 测试数据库名称
		jdcA.setId("root");
		jdcA.setPassword("12345");
				
		cnA = jdcA.getConnection();  // 从数据源获取连接对象
        
		insertData(cnA);  // 调用方法插入数据			
		selectDatas(cnA);    // 调用方法查询数据
		
		try {
    
    
			if(cnA!=null) {
    
    
				if(cnA.isClosed()==false) {
    
    
					cnA.close();  // 关闭连接对象
				}
			}
			cnA = null;
		}catch(SQLException e) {
    
    
			e.printStackTrace();
		}		
	}
	
	/**
	 * 查询数据
	 * @param cn 连接对象
	 * */
	private static void selectDatas(Connection cn) {
    
    
		StringBuffer sbA = null;
		PreparedStatement pst = null;
		ResultSet rs = null;
		
		try {
    
    			
			// 1.  构造SQL语句:
			sbA = new StringBuffer();
			sbA.append("Select * from tbStudent ");
			sbA.append("Where id = ?");  // ? 参数占位符
			
			// 2. 创建预编译命令对象:
			pst = cn.prepareStatement(sbA.toString());
			// 3. 根据需要设置参数的值:
			pst.setString(1, "201802"); 			
			// 4. 执行查询,获取结果集::
			rs = pst.executeQuery();
			
			// 5. 显示结果集记录:
			Object oVal = null;    // 临时对象变量
			String strVal = null;  // 存储字段值
			if(rs!=null) {
    
    
				while(rs.next()) {
    
      // 定位记录指针
					for(int i=1;i<=rs.getMetaData().getColumnCount();i++) {
    
    
						oVal = rs.getObject(i);  // 字段索引值从1开始!
						if(oVal!=null) {
    
    
							strVal = oVal.toString();
						}else {
    
    
							strVal = "  ";
						}
						System.out.print(strVal + "  ");
					}
					System.out.println();  // 换行
				}				
			}
			
		}catch(SQLException e) {
    
    
			e.printStackTrace();
		}finally {
    
    
			try {
    
    
				if(rs!=null && rs.isClosed()==false) {
    
    
					rs.close();   // 关闭结果集
				}
				if(pst!=null) {
    
    
					pst.close();  // 关闭命令对象
				}				
				pst = null;
			}catch(SQLException e) {
    
    
				e.printStackTrace();
			}
		}		
	}
	
	/**
	 * 插入数据
	 * @param cn 连接对象
	 * */
	private static void insertData(Connection cn) {
    
    
		StringBuffer sbA = null;
		PreparedStatement pst = null;
		
		try {
    
    			
			// 1、构造SQL语句:
			sbA = new StringBuffer();
			sbA.append("Insert Into tbStudent(");
			sbA.append("id,name,age,classId) Values(");
			sbA.append("'201806',");
			sbA.append("'王五',");
			sbA.append("19,");
			sbA.append("'1909'");
			sbA.append(")");
						
			// 2、 创建命令对象:
			pst = cn.prepareStatement(sbA.toString());
			boolean b = pst.execute();    // 3、执行命令语句
			int r = pst.getUpdateCount(); // 获取更新记录的条数		
			if(r>0) {
    
    
				System.out.println("插入数据成功!");
			}
			
		}catch(SQLException e) {
    
    
			e.printStackTrace();
		}finally {
    
    
			try {
    
    
				if(pst!=null) {
    
    
					pst.close();  // 关闭命令对象
				}				
				pst = null;
			}catch(SQLException e) {
    
    
				e.printStackTrace();
			}
		}
	}
	
	
}

猜你喜欢

转载自blog.csdn.net/qq_44723773/article/details/110490629