获取多个随机生成的不重复的6位数,不重复的6位数或8位数串

获取多个随机生成的6位数,每次获取都不会与前一次重复 

思路1:创建一张表table,每次生成一条之后,查询一下表中是否已存在这样的话,数据越来越多,后面就挺麻

烦的,判断多次才能取到一个表中不存在的 

思路2:建议一次性在数据库表中插入多条数据(如10000条), 表名table、主键自增长id、随机数:randoms,

编写程序 执行insert 语句插入 然后创建一个sequence,从1开始,步数为1 

select randoms from table where id = (select sequence.nextval from dual);

SQL如下:

drop table tbl_random;
create table tbl_random(
    id int not null auto_increment,
    num varchar(6),
    misc varchar(10),
    primary key(id)
);
insert into tbl_random(num,misc) values('098787','000');

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Test {
	static PreparedStatement pre = null;
	static ResultSet rs = null;

	public static void main(String[] args) {
		for (int i = 0; i < 100; i++) {
			String result = new Test().getRandom();
			System.out.println(result);
			while (exits(result) == 0) {
				execInsert(result);
				break;
			}
		}
	}

	public String getRandom() {
		String result = "";
		// 下面的6改成8就是8位随机数字
		while (result.length() < 6) {
			String str = String.valueOf((int) (Math.random() * 10));
			if (result.indexOf(str) == -1) {
				result += str;
			}
		}
		return result;
	}

	public static int exits(String num) {
		try {
			String sql2 = "select * from tbl_random where num='" + num +"'";
			pre = getConnect().prepareStatement(sql2);
			rs = pre.executeQuery();
			System.out.println(sql2);

			List> list = new ArrayList>();
			ResultSetMetaData md = rs.getMetaData();
			int count = md.getColumnCount();
			while (rs.next()) {
				Map rowData = new HashMap();
				for (int i = 1; i <= count; i++) {
					rowData.put(md.getColumnName(i), rs.getObject(i));
				}
				list.add(rowData);
			}
			if (list.size() > 0) {
				return 1;
			}else{
				return 0;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return 0;
	}

	public static void execInsert(String str) {
		try {
			String sql = "insert into tbl_random(num,misc) values(?,?)";
			pre = getConnect().prepareStatement(sql);
			pre.setString(1, str);
			pre.setString(2, "--");
			pre.executeUpdate();
			System.out.println(sql);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static Connection getConnect() {
		String Driver = "com.mysql.jdbc.Driver";
		String url = "jdbc:mysql://localhost:3306/test";
		String user = "root";
		String password = "pwd";
		Connection con = null;
		try {
			Class.forName(Driver).newInstance();
			con = DriverManager.getConnection(url, user, password);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return con;
	}
}


你可能感兴趣的:(My,Java,life,排序/算法)