学大数据分析的同学们在做数据分析时一般很难找到适合数据集,本文就来分享一下如何利用Java模拟数据,并将产生数据保存至mysql数据库中。
主要技术就是Java产生数据,利用mybatis存入mysql数据库
数据模拟项目
- 1.数据库建表
- 2.构建maven项目
- 3.项目结构
- 4.编写实体类和工具类
- a.实体类
- b.随机生成地址
- c.随机生成姓名
- d.随机生成电子邮件
- e.随机生成电话号码
- f.随机生成日期
- g.生成工资
- h.生成1-10随机数
- i.获取sqlSession工具类
- 5.生成数据并插入mysql数据库
- a.TeacherMapper接口
- b.TeacherMapper.xml
- c.test 类实现生成并插入
- 6.写在最后
1.数据库建表
模拟之前需要建表:也就是说你要模拟什么数据就建对应的表
本次模拟的数据是教师相关信息
建数据库teacher,建表teacher
可以利用第三方工具也可以,通过执行sql
sql:
CREATE DATABASE /*!32312 IF NOT EXISTS*/`teacher` /*!40100 DEFAULT CHARACTER SET utf8 */ /*!80016 DEFAULT ENCRYPTION='N' */;
USE `teacher`;
/*Table structure for table `teacher` */
DROP TABLE IF EXISTS `teacher`;
CREATE TABLE `teacher` (
`id` int unsigned NOT NULL AUTO_INCREMENT COMMENT '教师编号',
`name` varchar(255) DEFAULT NULL COMMENT '教师姓名',
`phone` varchar(255) DEFAULT NULL COMMENT '教师手机号',
`email` varchar(255) DEFAULT NULL COMMENT '电子邮件',
`address` varchar(255) DEFAULT NULL COMMENT '家庭地址',
`time` varchar(255) DEFAULT NULL COMMENT '时间',
`salary` varchar(255) DEFAULT NULL COMMENT '工资',
`random` int DEFAULT NULL COMMENT '随机生成1-10的数',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3;
2.构建maven项目
打开idea建一个maven项目,项目名随便命名
结构如下:
导入依赖:pom文件如下
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>Data</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.1</version>
<scope>test</scope>
</dependency>
<!-- Mybatis核心 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.10</version>
</dependency>
<!-- MySQL驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.29</version>
</dependency>
</dependencies>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
</project>
3.项目结构
结构图示:
ming.txt
冠钧 子阳 晨君 泓铭 琦霖 诗雨 语桐 奕骁 子鑫 宗鑫 政尚 桐畅 楷瑞 栩安 伟桐 栩昊 璟弘 羽洋 翊宁 锡麟 以钦 俊皓 允泽 南柔 启元 德凯 振烨 梓硕 璟文 翊涛 承烨 钰睿 宇轩 宸源 朝义 一桐 亦程 君睿 启鑫 小西 昱硕 梓熙 歆焱 洛颜 熙宸 瑜文 鑫龙 颢程 亦泽 俊伟 俊宁 俊希 健慧 吉洋 咏腾 嘉翔 奕然 家翊 家茗 小祺 少博 恩康 承允 文乐 易瑞 景潇 松睿 林枫 楚天 沐灵 泽豪 浩淼 清楚 瀚宇 玖辰 睿涵 睿熙 维宁 誉喆 诺迪 贤俊 轩彬 轩昂 逸楠 逸铭 金淼 锡梵 锦凡 靖翔 骏琪 鸣钥 鹏宇 一航 语鑫 铭誉 麒瑞 晗君 楷翔 嘉豪
xing.txt
赵 钱 孙 李 周 吴 郑 王 冯 陈 褚 卫 蒋 沈 韩 杨 朱 秦 尤 许 何 吕 施 张 孔 曹 严 华 金 魏 陶 姜 戚 谢 邹 喻 柏 水 窦 章 云 苏 潘 葛 奚 范 彭 郎 鲁 韦 昌 马 苗 凤 花 方 俞 任 袁 柳 酆 鲍 史 唐 费 廉 岑 薛 雷 贺 倪 汤 滕 殷 罗 毕 郝 邬 安 常 乐 于 时 傅 皮 卞 齐 康 伍 余 元 卜 顾 孟 平 黄 和 萧 尹 湛 汪 祁 毛 禹 狄 米 贝 成 戴 谈 宋 茅 庞 熊 纪 舒 屈 项 祝 董 梁 杜 阮 蓝 闵 席 季 麻 强 贾 路 娄 危 江 童 颜 郭 梅 盛 林 刁 钟 徐 邱 骆 高 夏 蔡 田 樊 胡 凌 霍 虞 万 支 柯 昝 管 卢 莫 白 房 裘 缪 干 解 应 宗 丁 宣 贲 邓 郁 单 杭 洪 包 诸 左 石 崔 吉 钮 龚 程 嵇 邢 滑 裴 陆 荣 翁 荀 羊
mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--设置连接数据库的环境-->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/teacher?characterEncoding=utf8"/>
<property name="username" value="root"/>
<property name="password" value="021806"/>
</dataSource>
</environment>
</environments>
<!--引入映射文件-->
<mappers>
<mapper resource="mappers/TeacherMapper.xml"/>
</mappers>
</configuration>
这里要注意mysql密码改成自己的
4.编写实体类和工具类
实体类与mysql数据库中的表对应
工具类是用于模拟生成数据的
a.实体类
package com.li.pojo;
public class Teacher {
private int uid;
private String name;
private String phone;
private String email;
private String address;
private String time;
private String salary;
private int random;
public Teacher() {
}
public int getUid() {
return uid;
}
public void setUid(int uid) {
this.uid = uid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getSalary() {
return salary;
}
public void setSalary(String salary) {
this.salary = salary;
}
public int getRandom() {
return random;
}
public void setRandom(int random) {
this.random = random;
}
@Override
public String toString() {
return "Teacher{" +
"uid=" + uid +
", name='" + name + '\'' +
", phone='" + phone + '\'' +
", email='" + email + '\'' +
", address='" + address + '\'' +
", time='" + time + '\'' +
", salary='" + salary + '\'' +
", random=" + random +
'}';
}
public Teacher(int uid, String name, String phone, String email, String address, String time, String salary, int random) {
this.uid = uid;
this.name = name;
this.phone = phone;
this.email = email;
this.address = address;
this.time = time;
this.salary = salary;
this.random = random;
}
}
b.随机生成地址
package com.li.Utils;
import java.util.Random;
public class AdressUtils {
public static String getProCity(){
String[] province = {"河北省","山西省","辽宁省","吉林省","黑龙江","江苏省","浙江省","安徽省","福建省","江西省","山东省","河南省","湖北省","湖南省","广东省","海南省","四川省","贵州省","云南省","陕西省","甘肃省","青海省","台湾省","北京市","天津市","广西省","内蒙古","宁夏省","新疆省","上海市","香港区","澳门区","重庆市","西藏市",};
String[] city = {"安康市","安庆市","安顺市","安阳市","鞍山市","巴彦淖尔市","巴中市","白城市","白山市","白银市","百色市","蚌埠市","包头市","宝鸡市","保定市","保山市","北海市","本溪市","滨州市","沧州市","昌都地区","长春市","长沙市","长治市","常德市","常州市","巢湖市","朝阳市","潮州市","郴州市","成都市","承德市","池州市","赤峰市","崇左市","滁州市","达州市","大连市","大庆市","大同市","丹东市","德阳市","德州市","定西市","东莞市","东营市","鄂尔多斯市","鄂州市","防城港市","佛山市","福州市","抚顺市","抚州市","阜新市","阜阳市","甘南州","赣州市","固原市","广安市","广元市","广州市","贵港市","贵阳市","桂林市","哈尔滨市","哈密地区","海北藏族自治州","海东地区","海口市","邯郸市","汉中市","杭州市","毫州市","合肥市","河池市","河源市","菏泽市","贺州市","鹤壁市","鹤岗市","黑河市","衡水市","衡阳市","呼和浩特市","呼伦贝尔市","湖州市","葫芦岛市","怀化市","淮安市","淮北市","淮南市","黄冈市","黄山市","黄石市","惠州市","鸡西市","吉安市","吉林市","济南市","济宁市","佳木斯市","嘉兴市","嘉峪关市","江门市","焦作市","揭阳市","金昌市","金华市","锦州市","晋城市","晋中市","荆门市","荆州市","景德镇市","九江市","酒泉市","开封市","克拉玛依市","昆明市","拉萨市","来宾市","莱芜市","兰州市","廊坊市","乐山市","丽江市","丽水市","连云港市","辽阳市","辽源市","聊城市","临沧市","临汾市","临沂市","柳州市","六安市","六盘水市","龙岩市","陇南市","娄底市","泸州市","吕梁市","洛阳市","漯河市","马鞍山市","茂名市","眉山市","梅州市","绵阳市","牡丹江市","内江市","南昌市","南充市","南京市","南宁市","南平市","南通市","南阳市","宁波市","宁德市","攀枝花市","盘锦市","平顶山市","平凉市","萍乡市","莆田市","濮阳市","普洱市","七台河市","齐齐哈尔市","钦州市","秦皇岛市","青岛市","清远市","庆阳市","曲靖市","衢州市","泉州市","日照市","三门峡市","三明市","三亚市","汕头市","汕尾市","商洛市","商丘市","上饶市","韶关市","邵阳市","绍兴市","深圳市","沈阳市","十堰市","石家庄市","石嘴山市","双鸭山市","朔州市","四平市","松原市","苏州市","宿迁市","宿州市","绥化市","随州市","遂宁市","台州市","太原市","泰安市","泰州市","唐山市","天水市","铁岭市","通化市","通辽市","铜川市","铜陵市","铜仁市","吐鲁番地区","威海市","潍坊市","渭南市","温州市","乌海市","乌兰察布市","乌鲁木齐市","无锡市","吴忠市","芜湖市","梧州市","武汉市","武威市","西安市","西宁市","锡林郭勒盟","厦门市","咸宁市","咸阳市","湘潭市","襄樊市","孝感市","忻州市","新乡市","新余市","信阳市","兴安盟","邢台市","徐州市","许昌市","宣城市","雅安市","烟台市","延安市","盐城市","扬州市","阳江市","阳泉市","伊春市","伊犁哈萨克自治州","宜宾市","宜昌市","宜春市","益阳市","银川市","鹰潭市","营口市","永州市","榆林市","玉林市","玉溪市","岳阳市","云浮市","运城市","枣庄市","湛江市","张家界市","张家口市","张掖市","漳州市","昭通市","肇庆市","镇江市","郑州市","中山市","中卫市","舟山市","周口市","株洲市","珠海市","驻马店市","资阳市","淄博市","自贡市","遵义市",};
String[] area = {"伊春区","带岭区","南岔区","金山屯区","西林区","美溪区","乌马河区","翠峦区","友好区","新青区","上甘岭区","五营区","红星区","汤旺河区","乌伊岭区","榆次区"};
String[] road = {"爱国路","安边路","安波路","安德路","安汾路","安福路","安国路","安化路","安澜路","安龙路","安仁路","安顺路","安亭路","安图路","安业路","安义路","安远路","鞍山路","鞍山支路","澳门路","八一路","巴林路","白城路","白城南路","白渡路","白渡桥","白兰路","白水路","白玉路","百安路(方泰镇)","百官街","百花街","百色路","板泉路","半淞园路","包头路","包头南路","宝安公路","宝安路","宝昌路","宝联路","宝林路","宝祁路","宝山路","宝通路","宝杨路","宝源路","保德路","保定路","保屯路","保屯路","北艾路",};
String[] home = {"金色家园","耀江花园","阳光翠竹苑","东新大厦","溢盈河畔别墅","真新六街坊","和亭佳苑","协通公寓","博泰新苑","菊园五街坊","住友嘉馨名园","复华城市花园","爱里舍花园"};
Random random = new Random();
int randomProvinceNum = random.nextInt(province.length);
int randomCityNum = random.nextInt(city.length);
int randomAreaNum = random.nextInt(area.length);
int randomRoadNum = random.nextInt(road.length);
int randomHomeNum = random.nextInt(home.length);
int num = random.nextInt(200);
return province[randomProvinceNum]+city[randomAreaNum]+area[randomAreaNum]+road[randomRoadNum]+num+"号"+home[randomHomeNum];
}
}
c.随机生成姓名
package com.li.Utils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.Random;
public class NameUtils {
public static String GetName(){
String name = getXing().concat(getMing());
return name;
}
// 从数据中 获取名字
public static String getMing(){
String ming = readFile("D:\\JavaProject\\Data\\src\\main\\java\\com\\li\\data\\ming.txt");
// System.out.println(ming);
String[] mings = ming.split(" ");
Random rd = new Random();
String mm = mings[rd.nextInt(mings.length)];
return mm;
}
// 从百家姓中 获取一个 姓
public static String getXing(){
String xx = readFile("D:\\JavaProject\\Data\\src\\main\\java\\com\\li\\data\\xing.txt");
// System.out.println(xx);
String[] xings = xx.split(" ");
Random rd = new Random();
String x = xings[rd.nextInt(xings.length)];
return x;
}
// 读取文档中的内容,一行一行读取的
public static String readFile(String path){
File file = new File(path);
StringBuilder result = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file),"UTF-8"));
String s = null;
while ((s=br.readLine())!=null){
result.append(System.lineSeparator()+s);
}
br.close();
}catch (Exception e){
System.err.println("获取文件失败!!!");
}
return result.toString();
}
}
d.随机生成电子邮件
package com.li.Utils;
import java.util.Random;
public class EmailUtils {
public static String GetEmail(){
String email = getTel().concat(getCom());
return email;
}
public static String getCom(){
String[] year = {"@qq.com","@163.com","@yahoo.cn","@sina.com","@gmail.com",};
Random random = new Random();
int year1 = random.nextInt(year.length);
return "."+year[year1];
}
public static String getTel(){
Random rd = new Random();
String tel;
String[] num1 = {"2","4","6","8"};
String[] num2 = {"1","3","5","7"};
tel = num1[rd.nextInt(4)] + num2[rd.nextInt(4)];
for (int i=0;i<5;i++){
int num = rd.nextInt(10);
tel = tel + num;
}
return tel;
}
}
e.随机生成电话号码
package com.li.Utils;
import java.util.Random;
public class PhoneUtils {
// IP、状态码、 性别
// 随机生成手机号11位 1 [3,5,7,8] 0-9
public static String getTel(){
Random rd = new Random();
String tel = "1";
String[] num2 = {"3","5","7","8"};
tel = tel + num2[rd.nextInt(4)];
for (int i=0;i<9;i++){
int num = rd.nextInt(10);
tel = tel + num;
}
return tel;
}
}
f.随机生成日期
package com.li.Utils;
import java.util.Random;
public class TimeUtils {
public static String Time(){
String[] year = {"2016","2017","2018","2019","2020","2021","2022",};
String[] mounth = {"01","02","03","04","05","06","07","08","09","10","11","12",};
String[] day = {"01","02","03","04","05","06","07","08","09","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30",};
Random random = new Random();
int year1 = random.nextInt(year.length);
int mounth1 = random.nextInt(mounth.length);
int day1 = random.nextInt(day.length);
return year[year1]+"-"+mounth[mounth1]+"-"+day[day1];
}
}
g.生成工资
package com.li.Utils;
import java.util.Random;
public class SalaryUtils {
public static String getSalary(){
String[] salary = {"4500","6500","8000","10000","12000","18000","20000",};
Random random = new Random();
int salary1 = random.nextInt(salary.length);
return salary[salary1]+"元";
}
}
h.生成1-10随机数
package com.li.Utils;
import java.util.Random;
public class NumUtils {
public static int Num(){
Random random = new Random();
int a = random.nextInt(10)+1;
return a;
}
}
i.获取sqlSession工具类
package com.li.Utils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
public class GetSqlSession {
public static SqlSession getSqlSession(){
try {
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
//4.mybatis-config.xml
SqlSession sqlSession = sqlSessionFactory.openSession(true);
return sqlSession;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
5.生成数据并插入mysql数据库
a.TeacherMapper接口
package com.li.mapper;
import com.li.pojo.Teacher;
public interface TeacherMapper {
int insertTeacher(Teacher teacher);
int add();
}
b.TeacherMapper.xml
这里id自增
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--insert into teacher values (#{name},#{phone},#{email},#{age},#{offer},#{address},#{status},#{time},#{salary})-->
<mapper namespace="com.li.mapper.TeacherMapper">
<insert id="insertTeacher" parameterType="com.li.pojo.Teacher">
insert into teacher (id ,name ,phone,email,address,time,salary,random)
values (null ,#{name},#{phone},#{email},#{address},#{time},#{salary},#{random})
</insert>
</mapper>
c.test 类实现生成并插入
通过for循环来指定生成数据的数量
package com.li;
import com.li.Utils.*;
import com.li.mapper.TeacherMapper;
import com.li.pojo.Teacher;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.Random;
public class test {
@Test
public void insertTest(){
for (int i=0;i<20;i++){
Teacher teacher = new Teacher();
teacher.setName(NameUtils.GetName());
teacher.setPhone(PhoneUtils.getTel());
teacher.setEmail(EmailUtils.GetEmail());
teacher.setAddress(AdressUtils.getProCity());
teacher.setTime(TimeUtils.Time());
teacher.setSalary(SalaryUtils.getSalary());
teacher.setRandom(NumUtils.Num());
SqlSession sqlSession = GetSqlSession.getSqlSession();
TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
System.out.println(i);
int a = mapper.insertTeacher(teacher);
}
}
}
查看数据库
6.写在最后
数据都是模拟产生的,数据不是很准确,但是可以做为练习,想生成其它数据可以把这个作为模板来改进!
项目也有很多改进的地方,比如日期,地址,也可以改成类似与生成姓名那种形式,这样就可以避免地址重复,时间不准确
也可以当作一个Java小项目练习。
项目源码地址:
大家可以下载并改正!