java连接数据库进行增添数据的不同写法

本文介绍了一种使用Java进行数据库操作的方法,包括通过属性文件配置数据库连接,并利用PreparedStatement执行SQL语句来实现员工信息的添加。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、

//连接数据库工具类

jdbc.properties:

driver = com.mysql.jdbc.Driver
url = jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8
user = root
pass =123456
DBConnectionUtil:

public static Connection getConnection() throws Exception{
		Connection conn = null;
		try {
			//加载属性文件,读取数据库连接配置信息
			Properties pro = new Properties();
			try {
				pro.load(GetConn.class.getResourceAsStream("/jdbc.properties"));
			} catch (IOException e) {
				System.out.println("未找到配置文件!!!");
			}
			String url = pro.getProperty("url");
			String user = pro.getProperty("user");
			String pass = pro.getProperty("pass");
			Class.forName(pro.getProperty("driver"));
			conn = DriverManager.getConnection(url, user, pass);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return conn;
	}
EmpDao:

//添加员工
	public boolean saveEmp(){
		boolean flag = false;
		Connection conn = null; 
		Statement st = null;
		try {
			//加载驱动
			Class.forName(jdbcDriver);
			conn = DriverManager.getConnection(jdbcUrl,jdbcUser,jdbcPass);
			String sql = "insert into emp values('7777','LZH','manger',"+null+",'2017-10-1','90000','10000','10')";
			st = conn.createStatement();
			int result = st.executeUpdate(sql);
			if(result > 0){
				flag = true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				st.close();
			} catch (SQLException e) {
				
				e.printStackTrace();
			} finally {
				if(conn != null){
					try {
						conn.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				}
			}
		}
		return flag;
	}


二、

EmpDao:

public boolean saveEmp2(Emp emp){
			boolean flag = false;
			Connection conn = null; 
			PreparedStatement ps = null;//预编译结果集
			try {
				//加载驱动
				conn = DBConnectionUtil.getConnection();
				String sql = "insert into emp values (?,?,?,?,?,?,?,?)";
				ps = conn.prepareStatement(sql);
				ps.setInt(1, emp.getEmpno());
				ps.setInt(4, emp.getMgr());
				ps.setInt(6, emp.getSal());
				ps.setInt(8, emp.getDeptno());
				ps.setString(2, emp.getEname());
				ps.setString(3, emp.getJob());
				ps.setString(5, emp.getHiredate());
				ps.setInt(7, emp.getComm());
				int result = ps.executeUpdate();
				if(result > 0){
					flag = true;
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				DBConnectionUtil.closeAll(ps, conn);
			}
			return flag;
		}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

张小帅和刘美美

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值