会员可以在此提问,百战程序员老师有问必答
对大家有帮助的问答会被标记为“推荐”
看完课程过来浏览一下别人提的问题,会帮你学得更全面
截止目前,同学们一共提了 132360个问题

package com.bjsxt;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * preparedStatement对象的使用
 * @author tui
 *
 */
public class PreparedStatementDemo {
	
	//向departments表插入一条数据
	public void insertDepartments(String departmentName,int locationId) {
		Connection conn=null;
		PreparedStatement ps=null;
		try {
			conn = JdbcUtil.getConnection();
			ps = conn.prepareStatement("insert into departments values(default,?,?)");
			ps.setString(1, departmentName);
			ps.setInt(2, locationId);
			ps.execute();
		} catch (Exception e) {
			// TODO: handle exception
		}finally {
			JdbcUtil.closeResource( ps, conn, null);
		}
	}
	//数据更新
	public void updateDepartments(int departmentId,String departmentName,int localhostId) {
		Connection conn=null;
		PreparedStatement ps=null;
		try {
			conn = JdbcUtil.getConnection();
			ps=conn.prepareStatement("update departments set department_name=?,location_id=? where department_id=?");
			ps.setString(1, departmentName);
			ps.setInt(2, localhostId);
			ps.setInt(3, departmentId);
			ps.execute();
		} catch (Exception e) {
			// TODO: handle exception
		}finally {
			JdbcUtil.closeResource(ps, conn, null);
		}
	} 
	//查询数据
	public Departments selectDepartmentsById(int departmentId) {
		Connection conn=null;
		PreparedStatement ps=null;
		ResultSet rs=null;
		Departments dept=null;
		try {
			conn=JdbcUtil.getConnection();
			ps=conn.prepareStatement("select * from departemnts where department_id=?");
			ps.setInt(1, departmentId);
			rs=ps.executeQuery();
			while (rs.next()) {
				dept =new Departments();
				dept.setDepartmentId(rs.getInt("department_id"));
				dept.setDepartmentName(rs.getString("department_name"));
				dept.setLocationId(rs.getInt("location_id"));				
			}
		} catch (Exception e) {
			// TODO: handle exception
		}finally {
			JdbcUtil.closeResource(ps, conn, rs);
		}
		return dept;
	}
	public static void main(String[] args) {
		PreparedStatementDemo demo=new PreparedStatementDemo();
		//demo.insertDepartments("人力资源10", 10);
		//demo.updateDepartments(9, "人力资源20", 20);
		Departments dept=demo.selectDepartmentsById(10);
			if (dept!=null) {
				System.out.println(dept.getDepartmentId()+" "+dept.getDepartmentName()+" "+dept.getLocationId());
			}		
	}
}

老师,为什么查询数据selectDepartmentsById这个方法测试报空指针异常(主方法里把if条件删了报空指针异常)

JAVA 全系列/第三阶段:数据库编程/JDBC技术(旧) 1592楼
JAVA 全系列/第三阶段:数据库编程/Oracle 数据库的使用 1594楼
JAVA 全系列/第三阶段:数据库编程/SQL 语言 1596楼
JAVA 全系列/第三阶段:数据库编程/SQL 语言 1600楼
JAVA 全系列/第三阶段:数据库编程/MySQL数据库的使用 1601楼
JAVA 全系列/第三阶段:数据库编程/MySQL数据库的使用 1602楼
JAVA 全系列/第三阶段:数据库编程/JDBC技术(旧) 1605楼

课程分类

百战程序员微信公众号

百战程序员微信小程序

©2014-2025百战汇智(北京)科技有限公司 All Rights Reserved 北京亦庄经济开发区科创十四街 赛蒂国际工业园
网站维护:百战汇智(北京)科技有限公司
京公网安备 11011402011233号    京ICP备18060230号-3    营业执照    经营许可证:京B2-20212637