您的位置:首页 > 产品设计 > UI/UE

java mysql batchquery批量添加

2016-09-29 15:29 218 查看
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(?,?,?,?)";
// 创建PreparedStatement
PreparedStatement ps = conn.prepareStatement(sql);
// 实例化Random
Random 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;
// 关闭PreparedStatement
ps.close();
// 关闭Connection
conn.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下,否则会报错

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: