java mysql batchquery批量添加

来源:互联网 发布:笔记本电脑散热器软件 编辑:程序博客网 时间:2024/06/06 07:49

1、效果图


2、Batch.java类

package com.hh;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.SQLException;import java.util.Random;/** * 批处理 * @author hh */public class Batch {/** * 获取数据库连接 * @return Connection对象 */public Connection getConnection(){// 数据库连接Connection conn = null;try {// 加载数据库驱动,注册到驱动管理器Class.forName("com.mysql.jdbc.Driver");// 数据库连接字符串String url = "jdbc:mysql://localhost:3306/hh";// 数据库用户名String username = "root";// 数据库密码String password = "root";// 创建Connection连接conn = DriverManager.getConnection(url,username,password);} catch (ClassNotFoundException e) {e.printStackTrace();} catch (SQLException e) {e.printStackTrace();}// 返回数据库连接return conn;}/** * 批量添加数据 * @return 所影响的行数 */public int saveBatch(){// 行数int row = 0 ;// 获取数据库连接Connection conn = getConnection();try {// 插入数据的SQL语句String sql = "insert into tb_student_batch(id,name,sex,age) values(?,?,?,?)";// 创建PreparedStatementPreparedStatement ps = conn.prepareStatement(sql);// 实例化RandomRandom random = new Random();// 循环添加数据for (int i = 0; i < 10; i++) {// 对SQL语句中的第1个参数赋值ps.setInt(1, i+1);// 对SQL语句中的第2个参数赋值ps.setString(2, "学生" + i);// 对SQL语句中的第3个参数赋值ps.setBoolean(3, i % 2 == 0 ? true : false);// 对SQL语句中的第4个参数赋值ps.setInt(4, random.nextInt(5) + 10);// 添加批处理命令ps.addBatch();}// 执行批处理操作并返回计数组成的数组int[] rows = ps.executeBatch();// 对行数赋值row = rows.length;// 关闭PreparedStatementps.close();// 关闭Connectionconn.close();} catch (Exception e) {e.printStackTrace();}// 返回添加的行数return row;}}
3、index.jsp页面

<%@page import="com.hh.Batch"%><%@ page language="java" contentType="text/html; charset=utf-8"    pageEncoding="utf-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"><title>Insert title here</title></head><body><jsp:useBean id="batch" class="com.hh.Batch"></jsp:useBean><%int row=batch.saveBatch();out.print("批量插入了["+row+"]条数据");%></body></html>

4、添加引用

住必须把mysql.jar包放到WebContent下的WEB-INF的lib下,否则会报错



1 0
原创粉丝点击