- import java.io.FileWriter;
- import java.sql.Connection;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.Map;
- import java.util.Map.Entry;
- import java.util.Scanner;
- import java.util.Set;
- public class Test {
- public static void main(String[] args) throws Exception {
- Scanner sc=new Scanner(System.in);
- Scanner sc2=new Scanner(System.in);
- //arrayList存储三个学生的信息
- ArrayList<Person> list=new ArrayList<>();
- for(int i=0;i<4;i++){
- System.out.println("请输入学生的姓名:");
- String name=sc.nextLine();
- System.out.println("请输入学生的年龄:");
- int age=sc2.nextInt();
- System.out.println("请输入学生的性别:");
- String sex=sc.nextLine();
- System.out.println("请输入学生的专业:");
- String study=sc.nextLine();
- list.add(new Person(name,age,sex,study));
- }
- // //循环遍历
- for (Person p : list) {
- System.out.println(p);
- }
- for (int i = 0; i < list.size(); i++) {
- System.out.println(list.get(i));
- }
- //获得数据库连接
- Connection conn=MyJDBCUtils.getConnection();
- PreparedStatement ps;
- //创建操作数据库的对象
- for (Person p : list) {
- String sql="insert into Person(pname,psex,page,pstudy) values('"+p.getName()+"','"+p.getSex()+"','"+p.getAge()+"','"+p.getPstudy()+"'); ";
- ps = conn.prepareStatement(sql);
- ps.executeUpdate(sql);
- }
- // 查询各个学科的人数
- String sql2="select count(*),pstudy from Person group by pstudy ";
- ps = conn.prepareStatement(sql2);
- ResultSet e= ps.executeQuery(sql2);
- while(e.next()){
- System.out.print(e.getInt(1)+" ");
- System.out.print(e.getString(2)+" ");
- System.out.println();
- }
-
- //提示用户输入三个id号(已有的) 将年龄改为66
- for(int i=0;i<3;i++){
- System.out.println("请输入已经存在的pid");
- int id=sc.nextInt();
- String sql3="update Person set page=66 where pid='"+id+"'";
- ps = conn.prepareStatement(sql3);
- ps.executeUpdate(sql3);
- }
- //将姓名作为键值 将科目作为 值放入map集合中
- Map<String,String> map=new HashMap<String, String>();
- String sql4="select pname,pstudy from Person ";
- ps=conn.prepareStatement(sql4);
- ResultSet re = ps.executeQuery(sql4);
- while(re.next()){
- map.put(re.getString(1), re.getString(2));
- }
- //遍历双列集合
- Set<String> set=map.keySet();
- for (String s : set) {
- System.out.println(s+"=="+map.get(s));
- }
- Set<Entry<String,String>> set2= map.entrySet();
- for (Entry<String, String> entry : set2) {
- System.out.println(entry.getKey()+"==="+entry.getValue());
- }
- //将表中的数据写入文件中
- String sql5="select * from Person ";
- ps=conn.prepareStatement(sql5);
- ResultSet re1 = ps.executeQuery(sql5);
- FileWriter fw=new FileWriter("temp.txt");
- while(re1.next()){
- fw.write(re1.getString("pid")+" ");
- fw.write(re1.getString("pname")+" ");
- fw.write(re1.getString("psex")+" ");
- fw.write(re1.getInt("page")+" ");
- fw.write(re1.getString("pstudy")+" \r\n");
-
- }
- fw.close();
- conn.close();
- ps.close();
- }
- }
复制代码 |