头歌实践Java项目开发入门实战第三阶段【Java高级特性】

本文来自头歌实践平台的Java项目实战入门【只有编程题】,如需访问其他阶段的文章,请自行阅读主页其他文章
制作不易,请留下一个免费的点赞以及关注吧!!!

一、Java高级特性-IO流

2、字节流-输入输出

package step2;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.BufferedReader;

import java.io.FileReader;

import java.io.IOException;

public class Task {

   

    public void task() throws IOException {

        /********* Begin *********/

       

        String inputFilePath = "src/step2/input/task.txt";

        String outputFilePath = "src/step2/output/output.txt";

        File inputFile = new File(inputFilePath);

        if (inputFile.exists()) {

            BufferedReader reader = new BufferedReader(new FileReader(inputFile));

            String line;

            while ((line = reader.readLine()) != null) {

                System.out.println(line);

            }

            reader.close();

        } else {

            System.out.println("输入文件不存在");

        }

        File outputDir = new File("src/step2/output");

        if (!outputDir.exists()) {

            outputDir.mkdirs();

        }

        File outputFile = new File(outputFilePath);

        FileOutputStream fos = new FileOutputStream(outputFile);

        String toWrite = "learning practice";

        byte[] buffer = new byte[8];

        int offset = 0;

        for (int i = 0; i < toWrite.length(); i++) {

            buffer[offset++] = (byte) toWrite.charAt(i);

            if (offset == 8) {

                fos.write(buffer);

                offset = 0;

            }

        }

        if (offset > 0) {

            fos.write(buffer, 0, offset);

        }

        fos.close();

       

        /********* End *********/

    }

   

}

3、字符流-输入输出 

package step3;

import java.io.BufferedReader;

import java.io.FileReader;

import java.io.FileWriter;

import java.io.IOException;

public class Task {

   

    public void task() throws IOException{

        /********* Begin *********/

        String inputFilePath = "src/step3/input/input.txt";

        String outputFilePath = "src/step3/output/output.txt";

       

        BufferedReader reader = new BufferedReader(new FileReader(inputFilePath));

        FileWriter writer = new FileWriter(outputFilePath);

       

        String line = reader.readLine();

       

        writer.write(line);

       

        reader.close();

        writer.close();

        /********* End *********/      

    }

}

4、复制文件 

package step4;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

public class Task {

   

    public void task() throws IOException{

        /********* Begin *********/

        try (FileInputStream fis = new FileInputStream("src/step4/input/input.txt");

             FileOutputStream fos = new FileOutputStream("src/step4/output/output.txt")) {

            byte[] buffer = new byte[1024];

            int bytesRead;

            while ((bytesRead = fis.read(buffer)) != -1) {

                fos.write(buffer, 0, bytesRead);

            }

        }

        try (FileInputStream fis = new FileInputStream("src/step4/input/input.jpg");

             FileOutputStream fos = new FileOutputStream("src/step4/output/output.jpg")) {

            byte[] buffer = new byte[1024];

            int bytesRead;

            while ((bytesRead = fis.read(buffer)) != -1) {

                fos.write(buffer, 0, bytesRead);

            }

        }

        /********* End *********/      

    }

}

二、Java高级特性-集合框架 (1)

1、集合的基本使用

package step1;

// 导包

/********** Begin **********/

import java.util.*;            

/********** End **********/

                       

public class HelloWorld {

   

    @SuppressWarnings("unchecked")

    public ArrayList getList() {

        /********** Begin **********/

        ArrayList list = new ArrayList();

        list.add("https:www.educoder.net");

        list.add(2018.423);

        return list;

       

        /********** End **********/

    }

   

}

 

2、ArrayList集合的增删改查 

package step2;

import java.util.ArrayList;

import java.util.Scanner;

public class HelloWorld {

   

    @SuppressWarnings("unchecked")

    public static void main(String[] args) {

        //获取输入的数据并添加至集合

        Scanner sc = new Scanner(System.in);

        ArrayList list = new ArrayList<>();

        int length = sc.nextInt();

        for(int i =0 ; i< length; i++){

            list.add(sc.next());

        }

        /********** Begin *********/

        //删除第一个/最后一个元素

        list.remove(0);

        int len  = list.size();

        list.remove(len-1);

        //list.remove(-1);

        list.add("hello");

        list.add("educoder");

        //修改第三个元素为list

        list.set(2,"list");

        for(int i =0;i

            System.out.println(list.get(i));

        }

        /********** End **********/

    }

}

3、集合的体系结构

package step3;

import java.util.ArrayList;

import java.util.HashSet;

import java.util.Set;

import java.util.HashMap;

import java.util.LinkedList;

import java.util.Map;

public class HelloWorld {

   

    public HashSet getHashSet(){

        /********** Begin **********/

        HashSet set = new HashSet();

        set.add("www.educoder.net");

        return set;

        /********** End **********/

    }

   

    public ArrayList getArrayList(){

        /********** Begin **********/

        ArrayList arr = new ArrayList();

        arr.add("www.educoder.net");

        return arr;

        /********** End **********/

    }

   

    public LinkedList getLinkedList(){

        /********** Begin **********/

        LinkedList list = new LinkedList();

        list.add("www.educoder.net");

       

        return list;

       

        /********** End **********/

    }

   

    public Map getHashMap(){

        /********** Begin **********/

        HashMap map = new HashMap();

        map.put("address","www.educoder.net");

        return map;

        /********** End **********/

    }  

}

 4、泛型

package step4;

import java.util.*;

public class HelloWorld {

   

   

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        //程序会输入三次数据

        /********** Begin **********/

        ArrayList arr = new ArrayList();

        for(int i = 0;i<3;i++){

            arr.add(sc.next());

        }

        for(int i = 0;i

            System.out.println("集合的第"+(i+1)+"个数据为:"+arr.get(i));

        }

        /********** End **********/

    }

   

}

 

5、Map集合的增删改查 

package step5;

import java.util.HashMap;

import java.util.Map;

import java.util.Scanner;

public class HelloWorld {

    public static void main(String[] args) {

        Map menuDict = new HashMap<>();

        Scanner sc = new Scanner(System.in);

        for (int i = 0; i < 5; i++) {

            menuDict.put(sc.next(),sc.nextInt());

        }

        /********** Begin **********/

        //添加菜名lamb,50

        menuDict.put("lamb",50);

        //获取fish的价格并打印

        System.out.println(menuDict.get("fish"));

        //修改fish价格

        menuDict.put("fish",100);

        //删除noodles这道菜

        menuDict.remove("noodles");

        //输出

        System.out.println(menuDict.toString());

        /********** End **********/

    }

   

}

三、Java 字符串与集合练习——词频统计 

1、单词分割

package step1;

import java.util.List;

import java.util.ArrayList;

import java.util.StringTokenizer;

public class StudentDemo{

    //使用String.split()方法分割

    public List splitPartition(String str){

        List list=new ArrayList();

               

        //请在此添加实现代码

        /********** Begin **********/

        String[] StrArr = str.split("\\|");        

        for(String Str : StrArr){

            list.add(Str);

        }

        /********** End **********/


 

        return list;

    }

    //使用StringTokenizer类进行分割

    public List tokenPartition(String str){

        List list=new ArrayList();

        //请在此添加实现代码

        /********** Begin **********/

        StringTokenizer strToken = new StringTokenizer(str,"?");

        while(strToken.hasMoreTokens()){

            list.add(strToken.nextToken());

        }

        /********** End **********/

        return list;

    }

}

2、确定单词在字符串中的位置 

package step2;

import java.util.Map;

import java.util.HashMap;

import java.util.StringTokenizer;

public class StudentDemo{

    //返回一个Map集合来得到单词和首次出现的下标  key为单词名称  value为单词的角标

    public Map getMap(String str){

        Map map = new HashMap();

        //对str进行分割   再加入map集合中

        //请在此添加实现代码

        /********** Begin **********/

        StringTokenizer st=new StringTokenizer(str);

                    String s;

                    while(st.hasMoreTokens()){

                        s=st.nextToken(" ,.\n");

                        int n=str.indexOf(s);

                        map.put(s,n);

                    }

        /********** End **********/

            return map;

            }

}

3、实现词频统计和排序输出 

package step3;

import java.util.Map;

import java.util.HashMap;

import java.util.StringTokenizer;

public class StudentDemo{

    //获取单词的数量

    public Map getWordCount(String str) {

        Map map = new HashMap();

       

    //请在此添加实现代码

    /********** Begin **********/

    StringTokenizer tokenizer=new StringTokenizer(new String (str));

    int count;

    String word;

    while(tokenizer.hasMoreTokens()){

        word=tokenizer.nextToken(" ,?.!:;\"\"‘’\n");

        if(map.containsKey(word)){

            count=map.get(word);

            map.put(word,count+1);

        }else{

            map.put(word,1);

        }

    }

    /********** End **********/

        return map;

    }

}

四、Java高级特性 - 多线程基础(1)使用线程 

1、创建线程

package step1;

//请在此添加实现代码

/********** Begin **********/

public class ThreadClassOne  extends Thread{

    public void run(){

        for(int i =0;i<=10;i++){

            if(i%2==1){

                System.out.print(i+" ");

            }else{

                continue;

            }

        }

    }

}


 

/********** End **********/

package step1;

//请在此添加实现代码

/********** Begin **********/

public class ThreadClassTwo  implements Runnable  {

    public void run(){

        for(int i=0;i<=10;i++){

            if(i%2==0){

                System.out.print(i+" ");

            }else{

                continue;

            }

           

        }

    }

}


 

/********** End **********/

 

 2、使用 Callable 和 Future 创建线程

package step2; //声明该类所在的包

import java.util.concurrent.Callable; //引入需要使用的类

import java.util.concurrent.FutureTask;

public class Task { //定义task类

    public void runThread(int num) { //定义runThread方法

        ThreadCallable callable = new ThreadCallable(num);

        FutureTask futureTask = new FutureTask<>(callable);

        Thread thread1 = new Thread(futureTask,"thread1");

       

        thread1.start(); // 启动线程

        try{ // 获取线程执行的结果

            System.out.println("线程的返回值为:"+futureTask.get());

        }catch(Exception e){

            e.printStackTrace();

        }

/********** End **********/

    }

}

//请在此添加实现代码

/********** Begin **********/

/* 在这里实现Callable接口及方法 */

class ThreadCallable implements Callable    {

    int num;

    ThreadCallable(int num){

        this.num = num;

    }    

    ThreadCallable(){

       

    }

    public Integer call() throws Exception{

        return getNum(num);

    }

    public int getNum(int num){

        if(num<3){

            return 1;

        }

        else{

            return getNum(num-1) +getNum(num-2);

        }

    }

}

/********** End **********/

五、Java高级特性 - 多线程基础(2)常用函数

2、常用函数(一)

package step2;

import java.util.Scanner;

public class Task {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        int num = sc.nextInt();

        MyThread myThread = new MyThread(num);

        myThread.start();

        try {

            myThread.join();

        } catch (InterruptedException e) {

            e.printStackTrace();

        }

        System.out.println("子线程计算结果为:" + myThread.getResult());

    }

}

/********** Begin **********/

class MyThread extends Thread {

    private int num;

    private long result;

    public MyThread(int num) {

        this.num = num;

    }

    @Override

    public void run() {

        result = fibonacci(num);

    }

    private long fibonacci(int n) {

        if (n <= 1) {

            return n;

        }

        long a = 0, b = 1, c;

        for (int i = 2; i <= n; i++) {

            c = a + b;

            a = b;

            b = c;

        }

        return b;

    }

    public long getResult() {

        return result;

    }

}

/********** End **********/

3、 常用函数(二)

package step3;

public class MyThread implements Runnable {

    private static final int COUNT = 5;

    private static int current = 0;

    private final int id;

    private static final Object lock = new Object();

    public MyThread(int id) {

        this.id = id;

    }

    @Override

    public void run() {

        for (int i = 0; i < COUNT; i++) {

            synchronized (lock) {

                while (current % 3 != id) {

                    try {

                        lock.wait();

                    } catch (InterruptedException e) {

                        e.printStackTrace();

                    }

                }

                if (id == 0) {

                    System.out.print("E");

                } else if (id == 1) {

                    System.out.print("D");

                } else if (id == 2) {

                    System.out.print("U");

                }

                current++;

                lock.notifyAll();

            }

        }

    }

    public static void main(String[] args) throws Exception {

        Thread threadE = new Thread(new MyThread(0));

        Thread threadD = new Thread(new MyThread(1));

        Thread threadU = new Thread(new MyThread(2));

        threadE.start();

        threadD.start();

        threadU.start();

        threadE.join();

        threadD.join();

        threadU.join();

        System.out.println();

    }

}

 六、Java高级特性 - 多线程基础(3)线程同步

2、使用synchronized关键字同步线程

package step2;

public class Task {

    public static void main(String[] args) {

       

        final insertData insert = new insertData();

       

        for (int i = 0; i < 3; i++) {

            new Thread(new Runnable() {

                public void run() {

                    insert.insert(Thread.currentThread());

                }

            }).start();

        }      

       

    }

}

class insertData{

   

    public static int num =0;

   

    /********* Begin *********/

    public synchronized void insert(Thread thread){

   

        for (int i = 0; i <= 5; i++) {

            num++;

            System.out.println(num);

        }

    }

    /********* End *********/

}

3、使用线程锁(Lock)实现线程同步 

package step3;

import java.util.concurrent.TimeUnit;

import java.util.concurrent.locks.Lock;

import java.util.concurrent.locks.ReentrantLock;

public class Task {

    public static void main(String[] args) {

        final Insert insert = new Insert();

        Thread t1 = new Thread(new Runnable() {

            public void run() {

                insert.insert(Thread.currentThread());

            }

        });

        Thread t2 = new Thread(new Runnable() {

            public void run() {

                insert.insert(Thread.currentThread());

            }

        });

        Thread t3 = new Thread(new Runnable() {

            public void run() {

                insert.insert(Thread.currentThread());

            }

        });

        // 设置线程优先级

        t1.setPriority(Thread.MAX_PRIORITY);

        t2.setPriority(Thread.NORM_PRIORITY);

        t3.setPriority(Thread.MIN_PRIORITY);

        t1.start();

        t2.start();

        t3.start();

    }

}

class Insert {

    public static int num;

    // 在这里定义Lock

    Lock lock = new ReentrantLock();

    public void insert(Thread thread) {

        /********* Begin *********/

        lock.lock();

        try{

            System.out.println(thread.getName()+"得到了锁");

            for (int i = 0; i < 5; i++) {

                num++;

                System.out.println(num);

        }

        }catch(Exception e){

            System.out.println(e);

        }finally{

            System.out.println(thread.getName()+"释放了锁");

            lock.unlock();

        }

       

       

       

        /********* End *********/

    }

}

4、使用volatile实现变量的可见性 

package step4;

public class Task {

    public volatile int inc = 0;

//请在此添加实现代码

/********** Begin **********/

    public synchronized void increase() {

        inc++;

    }


 

/********** End **********/

    public static void main(String[] args) {

        final Task test = new Task();

        for (int i = 0; i < 10; i++) {

            new Thread() {

                public void run() {

                    for (int j = 0; j < 1000; j++)

                        test.increase();

                };

            }.start();

        }

        while (Thread.activeCount() > 1) // 保证前面的线程都执行完

            Thread.yield();

        System.out.println(test.inc);

    }

}

七、Java高级特性 - 多线程练习题 

1、顺序输出

package step1;

public class Task {

    public static void main(String[] args) throws Exception {

        // 创建线程并设置线程名

        MyThread aa = new MyThread();

        aa.threadName = "AA";

        MyThread bb = new MyThread();

        bb.threadName = "BB";

        MyThread cc = new MyThread();

        cc.threadName = "CC";

       

        // 启动线程

        aa.start();

        bb.start();

        cc.start();

       

        // 等待所有线程执行完毕

        aa.join();

        bb.join();

        cc.join();

    }

}

class MyThread extends Thread {

    String threadName;

    private static String currentTurn = "AA";

    private static final Object lock = new Object();

    public void run() {

        int count = 5;

        while (count > 0) {

            synchronized (lock) {

                // 检查是否轮到自己执行

                while (!currentTurn.equals(threadName)) {

                    try {

                        lock.wait();

                    } catch (InterruptedException e) {

                        e.printStackTrace();

                    }

                }

                // 输出并更新当前轮次

                System.out.println("Java Thread" + threadName);

                currentTurn = nextThread(currentTurn);

                count--;

                lock.notifyAll();

            }

        }

    }

    // 确定下一个线程的名称

    private static String nextThread(String current) {

        switch (current) {

            case "AA":

                return "BB";

            case "BB":

                return "CC";

            case "CC":

                return "AA";

            default:

                return "";

        }

    }

}

2、售票窗口 

package step2;

public class Station extends Thread {    

    private static int tickets = 20;

    private static final Object lock = new Object();

    @Override

    public void run() {

        while (true) {

            synchronized (lock) {

                if (tickets <= 0) {

                    break;

                }

                System.out.println("卖出了第" + tickets + "张票");

                tickets--;

                if (tickets == 0) {

                    System.out.println("票卖完了");

                }

            }

            try {

                Thread.sleep(100);

            } catch (InterruptedException e) {

                e.printStackTrace();

            }

        }

    }

}

八、Java高级特性 - Java反射 

1、了解 Class 对象

package step1;

/**

 * 学员任务文件

 */

public class Reflect_stu {

    public static void main(String[] args) {

        System.out.println("通过Object 类中的 getClass() 获取的 Class 对象为:" + getPersonClass1());

        System.out.println("通过静态方法 Class.forName() 获取的 Class 对象为:" + getPersonClass2());

        System.out.println("通过类字面常量获取 Class 的对象为:" + getPersonClass3());

    }

    /**

     * 通过 Object 类中的 getClass() 获取的 Class 对象

     *

     * @return

     */

    public static Class getPersonClass1() {

        /********** Begin *********/

       

        return new Person().getClass();

        /********** End *********/

    }

    /**

     * 通过静态方法 Class.forName() 获取的 Class 对象

     *

     * 注意:Person 类的全路径为: step1.Person

     *

     * @return

     */

    public static Class getPersonClass2() {

        /********** Begin *********/

        Class clazz = null;

        try {

            clazz = Class.forName("step1.Person");

        } catch (ClassNotFoundException e) {

            e.printStackTrace();

        }

        return clazz;

        /********** End *********/

    }

    /**

     * 通过类字面常量获取 Class 的对象

     *

     * @return

     */

    public static Class getPersonClass3() {

        /********** Begin *********/

        Class clazz  = Person.class;

        return clazz;

        /********** End *********/

    }

}

2、利用反射分析类的能力 

package step2;

import java.lang.reflect.Constructor;

import java.lang.reflect.Field;

import java.lang.reflect.Method;

import java.lang.reflect.Modifier;

class Apple {

    private String name;

    public Apple(){}

    public Apple(String name){}

    public void setName(String name) {

        this.name = name;

    }

}

public class Reflect_stu {

    public static void main(String[] args) {

        // 请根据提供的 classPath 获取 step2.Apple 的 Class 对象, 请使用 Class.forName() 方法, 注意捕获异常

        // 通关之后,你也可以修改 clasapath 为其他类路径,分析某个类的能力, 例如: java.util.Date

        String classPath = "step2.Apple";

        Class clazz = null;

        /********** Begin *********/

        try

        {

            clazz=Class.forName(classPath);

        }catch(ClassNotFoundException e){

            e.printStackTrace();

        }

        /********** End *********/

        printFields(clazz);

        printConstructors(clazz);

        printMethods(clazz);

    }

   

    /**

     * 请打印类的每个域,输出格式为:修饰符 类型 变量名;

     * @param clazz

     */

    public static void printFields(Class clazz) {

        /********** Begin *********/

        try{

            Field[] fields=clazz.getDeclaredFields();

            for(Field field:fields)

            {

                System.out.print(Modifier.toString(field.getModifiers())+" ");

                System.out.print(field.getType().getTypeName()+" ");

                System.out.println(field.getName()+";");

            }

        }catch(Exception e)

        {

            e.printStackTrace();

        }

        /********** End *********/

    }

    /**

     * 打印构造函数,输出格式为:修饰符 方法名称(参数)

     * @param clazz

     */

    public static void printConstructors(Class clazz) {

        Constructor[] constructors = clazz.getDeclaredConstructors();

        for (Constructor constructor : constructors) {

            Class[] paramTypes = null;

            /********** Begin *********/

            paramTypes=constructor.getParameterTypes();

            System.out.print(Modifier.toString(constructor.getModifiers())+" ");

            System.out.print(constructor.getName()+"(");

            /********** End *********/

            printParamTypes(paramTypes);

        }

    }

    /**

     * 请针对每个方法打印其签名,格式为:修饰符 返回值类型 方法名称(参数);

     * @param clazz

     */

    public static void printMethods(Class clazz) {

        Method[] methos = clazz.getDeclaredMethods();

        for (Method method : methos) {

            Class[] paramTypes = null;

            /********** Begin *********/

            paramTypes=method.getParameterTypes();

            System.out.print(Modifier.toString(method.getModifiers()) + " " + method.getReturnType().getName() + " "+ method.getName() + "(");

            /********** End *********/

            printParamTypes(paramTypes);

        }

    }

    /**

     * 打印方法参数

     * @param paramTypes

     */

    private static void printParamTypes(Class[] paramTypes) {

        for (int j = 0; j < paramTypes.length; ++j) {

            if (j > 0) {

                System.out.print(",");

            }

            System.out.print(paramTypes[j].getName());

        }

        System.out.println(");");

    }

   

}

3、在运行时使用反射分析对象 

package step3;

import java.lang.reflect.AccessibleObject;

import java.lang.reflect.Field;

import java.lang.reflect.Modifier;

public class Reflect_stu {

    public static String toString(Object obj) {

        Class cl = obj.getClass();

        String r = "";

        r += "[";

        // 请获取所有 Field 并设置访问权限为 true

        /********** Begin *********/

        Field[] fields = null;

        fields=cl.getDeclaredFields();

        AccessibleObject.setAccessible(fields,true);

        /********** End *********/

        for (Field f : fields) {

            // 此处 if,逻辑为判断 Field 域是否为非静态域

            if (!Modifier.isStatic(f.getModifiers())) {

                if (!r.endsWith("[")) r += ",";

                r += f.getName() + "=";

                try {

                    // 请获取域的类型及值

                    /********** Begin *********/

                    Class t = null;

                    Object val = null;

                    t=f.getType();

                    val=f.get(obj);

                    /********** End *********/

                    // isPrimitive() 用于判断是否为基本数据类型,若为基础数据类型直接拼接,否则递归调用 toString 方法

                    if (t.isPrimitive()) r += val;

                    else r += toString(val);

                } catch (Exception e) {

                    e.printStackTrace();

                }

            }

        }

        r += "]";

        return r;

    }

    public static void main(String[] args) {

        Person person = new Person(88, 19, 175);

        System.out.println(toString(person));

    }

}

class Person {

    public Integer weight;

    private Integer age;

    private Double height;

    public Person(Integer weight, Integer age, double height) {

        this.weight = weight;

        this.age = age;

        this.height = height;

    }

}

4、利用反射进行方法调用 

package step4;

import java.lang.reflect.Constructor;

import java.lang.reflect.InvocationTargetException;

import java.lang.reflect.Method;

public class Reflect_stu {

    @SuppressWarnings("unchecked")

    public static void main(String[] args) throws InvocationTargetException {

        //使用反射调用

        Class clazz = null;

        try {

            clazz = Class.forName("step4.Apple");

            /********** Begin *********/

            Method setPriceMethod = clazz.getMethod("setPrice", double.class);

            Constructor appleConstructor = clazz.getConstructor();

            Object apple = appleConstructor.newInstance();

            setPriceMethod.invoke(apple, 14);

            Method getPriceMethod = clazz.getMethod("getPrice");

            System.out.println(getPriceMethod.invoke(apple));

            Method getTotal = clazz.getMethod("getTotal", double.class, int.class);

            System.out.println(getTotal.invoke(apple, 20, 24));

            /********** End *********/

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

}

class Apple {

    private double price;

    private int count;

    public Apple() {

    }

    public double getPrice() {

        return price;

    }

    public void setPrice(double price) {

        this.price = price;

    }

    public int getCount() {

        return count;

    }

    public void setCount(int count) {

        this.count = count;

    }

    public double getTotal(double price, int count) {

        return price * count;

    }

}

九、Java高级特性 - JDBC(上) 

1、JDBC连接数据库

package jdbc;

import java.sql.*;

public class jdbcConn {

    public static void getConn() {

        /**********    Begin   **********/

        try {

            //1.注册驱动

            Class.forName("com.mysql.jdbc.Driver");

        } catch (ClassNotFoundException e) {

            e.printStackTrace();

        };

        /**********    End   **********/

        /**********    Begin   **********/

        Connection conn = null;

        Statement statement = null;

        //2.建立连接并创建数据库和表

        String url = "jdbc:mysql://localhost:3306";

        String user = "root";

        String password = "123123";

        try{

            conn = DriverManager.getConnection(url, user, password);

            statement = conn.createStatement();

            String sql1 = "drop database if exists mysql_db";

            String sql2 = "create database mysql_db";

            statement.executeUpdate(sql1);

            statement.executeUpdate(sql2);

        } catch (SQLException e) {

            e.printStackTrace();

        }

        try{

            statement.executeUpdate("use mysql_db");

            String sql3 = "create table student(id int (11), name varchar(20), sex varchar(4), age int(11))";

            statement.executeUpdate(sql3);

        }catch (SQLException e)

            {

                e.printStackTrace();

            }

        /**********    End   **********/

        finally {

            try {

                if(statement!=null)

                    statement.close();

                if(conn!=null)

                    conn.close();

            } catch (SQLException e) {

                e.printStackTrace();

            }

        }

    }

}

2、JDBC对表中数据的操作 

package jdbc;

import java.sql.*;

import java.util.ArrayList;

import java.util.List;

public class jdbcInsert {

    public static void insert(){

        /**********   Begin  **********/

        try {

            //加载驱动

            Class.forName("com.mysql.jdbc.Driver");

        } catch (ClassNotFoundException e) {

            e.printStackTrace();

        }

        /**********   End   **********/

        Connection conn = null;

        PreparedStatement statement = null;

        /**********   Begin  **********/

        //连接并插入数据

        try{

            String url = "jdbc:mysql://localhost:3306/mysql_db?useUnicode=true&characterEncoding=utf8";

            String user = "root";

            String password = "123123";

            conn = DriverManager.getConnection(url, user, password);

            String sql = "insert into student(id,name,sex,age) values (1,'张三','男',19),(2,'李四','女',18),(3,'王五','男',20)";

            statement = conn.prepareStatement(sql);

            statement.executeUpdate();

            String sql1 = "select * from student";

            ResultSet rs = statement.executeQuery(sql1);

            Student student = null;

            while (rs.next()) {

                int id = rs.getInt(1);

                String name = rs.getString(2);

                String sex = rs.getString(3);

                int age = rs.getInt(4);

                student = new Student(id, name, sex, age);

                System.out.println(

                        student.getId() + " " + student.getName() + " " + student.getSex() + " " + student.getAge());

            }

       

        } catch (SQLException e) {

            e.printStackTrace();

        }

        /**********   End   **********/

        finally {

            try {

                if (statement != null)

                    statement.close();

                if (conn != null)

                    conn.close();

            } catch (SQLException e) {

                e.printStackTrace();

            }

        }

    }

}

3、JDBC事务 

package jdbc;

import java.sql.*;

public class jdbcTransaction {

    public static void transaction(){

        try {

            Class.forName("com.mysql.jdbc.Driver" );

        } catch (ClassNotFoundException e) {

            e.printStackTrace();

        }

        Connection conn = null;

        PreparedStatement ps = null;

        /**********  Begin   **********/

        //连接数据库并开启事务

        try {

            String url = "jdbc:mysql://localhost:3306/mysql_db?useUnicode=true&characterEncoding=utf8";

            conn = DriverManager.getConnection(url, "root", "123123");

            conn.setAutoCommit(false);

            String sql = "insert into student(id,name,sex,age) values(4,'赵六','女',21)";

            ps = conn.prepareStatement(sql);

            ps.executeUpdate();

            conn.commit();

            String sql1 = "daj;ljd";

            ps = conn.prepareStatement(sql1);

            ps.executeUpdate();

            conn.commit();

            String sql2 = "select * from student";

            ResultSet rs = ps.executeQuery(sql2);

            Student student = null;

            while (rs.next()) {

                int id = rs.getInt(1);

                String name = rs.getString(2);

                String sex = rs.getString(3);

                int age = rs.getInt(4);

                student = new Student(id, name, sex, age);

                System.out.println(

                        student.getId() + " " + student.getName() + " " + student.getSex() + " " + student.getAge());

            }

        } catch (SQLException e) {

            try {

                //回滚

                conn.rollback();

               

            } catch (SQLException e1) {

                e1.printStackTrace();

            }

        }

        /**********  End   **********/

        finally {

            try {

                if(ps!=null)

                    ps.close();

                if (conn != null)

                    conn.close();

            } catch (SQLException e1) {

                e1.printStackTrace();

            }

        }

    }

}

十、Java高级特性 - JDBC(下) 

1、指定类型JDBC封装

package step1;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.util.ArrayList;

import java.util.List;

import test.News;

public class JDBCUtils {

    /**

     * 连接数据库

     */

    private static Connection getConnection() {

        Connection conn = null;

        /********** Begin **********/

        String url = "jdbc:mysql://localhost:3306/mysql_db";

        try {

            Class.forName("com.mysql.jdbc.Driver");

            conn = DriverManager.getConnection(url, "root", "123123");

        } catch (ClassNotFoundException e) {

            e.printStackTrace();

        } catch (SQLException e) {

            e.printStackTrace();

        }

        /********** End **********/

        return conn;

    }

    /**

     * 更新数据方法

     *

     * @param news

     * @throws SQLException

     */

    public void update(News news) throws SQLException {

        Connection conn = getConnection();

        PreparedStatement ps = null;

        /********** Begin **********/

        String sql = "update news set title = ? ,author_name = ? where id = ? ";

        try {

            ps = conn.prepareStatement(sql);

            ps.setObject(1, news.getTitle());

            ps.setObject(2, news.getAuthor_name());

            ps.setObject(3, news.getId());

            ps.execute();

        } catch (SQLException e) {

            e.printStackTrace();

            throw new SQLException("更新数据失败");

        } finally {

            close(null, ps, conn);

        }

        /********** End **********/

    }

    /**

     * 查询所有数据

     *

     * @return

     * @throws SQLException

     */

    public List findAll() throws SQLException {

        Connection conn = getConnection();

        PreparedStatement ps = null;

        ResultSet rs = null;

        News news = null;

        List newsList = new ArrayList();

        /********** Begin **********/

        String sql = "select * from news";

        try {

            ps = conn.prepareStatement(sql);

            rs = ps.executeQuery();

            while (rs.next()) {

                news = new News(rs.getInt(1), rs.getString(2), rs.getString(3));

                newsList.add(news);

            }

        } catch (SQLException e) {

            e.printStackTrace();

            throw new SQLException("查询所有数据失败");

        } finally {

            close(rs, ps, conn);

        }

        /********** End **********/

        return newsList;

    }

    /**

     * 删除方法

     *

     * @param id

     * @throws SQLException

     */

    public void delete(int id) throws SQLException {

        Connection conn = getConnection();

        PreparedStatement ps = null;

        /********** Begin **********/

        String sql = "delete from news where id=?";

        try {

            ps = conn.prepareStatement(sql);

            ps.setObject(1, id);

            ps.execute();

        } catch (SQLException e) {

            e.printStackTrace();

            throw new SQLException(" 删除数据失败");

        } finally {

            close(null, ps, conn);

        }

        /********** End **********/

    }

    /**

     * 增加对象

     *

     * @param news

     * @throws SQLException

     */

    public void insert(News news) throws SQLException {

        Connection conn = getConnection();

        PreparedStatement ps = null;

        String sql = "insert into news(id,title,author_name)values(?,?,?)";

        try {

            ps = conn.prepareStatement(sql);

            ps.setInt(1, news.getId());

            ps.setString(2, news.getTitle());

            ps.setString(3, news.getAuthor_name());

            ps.executeUpdate();

        } catch (SQLException e) {

            e.printStackTrace();

            throw new SQLException("添加数据失败");

        } finally {

            close(null, ps, conn);

        }

    }

    /**

     * 根据id查询对象

     *

     * @param id

     * @return

     * @throws SQLException

     */

    public News findById(int id) throws SQLException {

        Connection conn = getConnection();

        PreparedStatement ps = null;

        ResultSet rs = null;

        News news = null;

        String sql = "select * from news where id=?";

        try {

            ps = conn.prepareStatement(sql);

            ps.setInt(1, id);

            rs = ps.executeQuery();

            if (rs.next()) {

                news = new News();

                news.setId(id);

                news.setTitle(rs.getString(2));

                news.setAuthor_name(rs.getString(3));

            }

        } catch (SQLException e) {

            e.printStackTrace();

            throw new SQLException("根据ID查询数据失败");

        } finally {

            close(rs, ps, conn);

        }

        return news;

    }

    /**

     * 关闭数据库连接

     *

     * @param rs

     * @param ps

     * @param conn

     */

    public static void close(ResultSet rs, PreparedStatement ps, Connection conn) {

        try {

            if (rs != null)

                rs.close();

            if (ps != null)

                ps.close();

            if (conn != null)

                conn.close();

        } catch (SQLException e) {

            e.printStackTrace();

        }

    }

}

2、泛型JDBC封装 

package step2;

import java.lang.reflect.Field;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.util.ArrayList;

import java.util.List;

public class JDBCUtils {

    private static Connection getConnection() {

        try {

            Class.forName("com.mysql.jdbc.Driver");

        } catch (ClassNotFoundException e) {

            e.printStackTrace();

        }

        String url = "jdbc:mysql://localhost:3306/mysql_db";

        Connection conn = null;

        try {

            conn = DriverManager.getConnection(url, "root", "123123");

        } catch (SQLException e) {

            e.printStackTrace();

        }

        return conn;

    }

    /**

     * 类名对应表,属性对应字段

     *

     * @param obj 传入的对象

     * @return

     */

    public void insert(Object obj) {

        Connection conn = getConnection(); // 连接数据库

        PreparedStatement ps = null;

        /********** Begin **********/

        try {

            String sql = "insert into ";

            String sql2 = ") values(";

            // 获取类名当表名

            String simpleName = obj.getClass().getSimpleName();

            sql += simpleName + "(";

            // 获取所有属性

            Field[] declaredFields = obj.getClass().getDeclaredFields();

            // 拼接sql语句

            for (int i = 0; i < declaredFields.length; i++) {

                sql += declaredFields[i].getName();

                sql2 += "?";

                if (i + 1 != declaredFields.length) {

                    sql += ",";

                    sql2 += ",";

                } else {

                    sql2 += ")";

                }

            }

            sql += sql2;

            ps = conn.prepareStatement(sql);

            // 填充占位符

            for (int i = 0; i < declaredFields.length; i++) {

                declaredFields[i].setAccessible(true);

                Object object = null;

                try {

                    object = declaredFields[i].get(obj);

                } catch (Exception e) {

                    e.printStackTrace();

                }

                ps.setObject(i + 1, object);

            }

            ps.execute();

        }

        /********** End **********/

        catch (SQLException e) {

            e.printStackTrace();

        } finally {

            close(null, ps, conn);

        }

    }

    /**

     * 通过对象的Class获取对应表中的所有记录

     *

     * @param c

     * @return

     */

    public List selectAll(Class c) {

        Connection conn = getConnection();

        List list = new ArrayList();

        PreparedStatement ps = null;

        ResultSet rs = null;

        /********** Begin **********/

        try {

            // 获取类名当作表名

            String simpleName = c.getSimpleName();

            // sql查询语句

            String sql = "select * from " + simpleName;

            ps = conn.prepareStatement(sql);

            // 获取结果集

            rs = ps.executeQuery();

            // 获取所有属性,对应结果集的所有列

            Field[] fields = c.getDeclaredFields();

            while (rs.next()) {

                // 创建对象

                T t = c.newInstance();

                // 给对象对应的属性赋值

                for (Field field : fields) {

                    field.setAccessible(true);

                    field.set(t, rs.getObject(field.getName()));

                }

                // 对象添加到集合

                list.add(t);

            }

        }

        /********** End **********/

        catch (Exception e) {

            e.printStackTrace();

        } finally {

            close(rs, ps, conn);

        }

        return list;

    }

    /**

     * 通过主键(默认第一个属性)删除对象

     *

     * @param obj

     * @return

     */

    public void delete(Object obj) {

        Connection conn = getConnection();

        PreparedStatement ps = null;

        /********** Begin **********/

        try {

            // 获取类名当作表明

            String simpleName = obj.getClass().getSimpleName();

            // 获取第一个属性的信息

            Field[] declaredFields = obj.getClass().getDeclaredFields();

            declaredFields[0].setAccessible(true);

            String name = declaredFields[0].getName();

            // sql删除语句

            String sql = "delete from " + simpleName + " where " + name + "=?";

            // 填充占位符

            ps = conn.prepareStatement(sql);

            ps.setObject(1, declaredFields[0].get(obj));

            ps.execute();

        }

        /********** End **********/

        catch (Exception e) {

            e.printStackTrace();

        } finally {

            close(null, ps, conn);

        }

    }

    /**

     * 模拟jdbc的更新操作,默认第一个属性为主键

     *

     * @param obj

     * @return

     */

    public void update(Object obj) {

        Class c = obj.getClass();// 获取obj的Class

        StringBuffer sb = new StringBuffer("update " + c.getSimpleName() + " set ");// 利用StringBuffer进行修改SQL语句的构造

        Field[] field = c.getDeclaredFields();// 通过反射获取对象的属性数组

        for (int i = 1; i < field.length; i++) {

            if (i != field.length - 1) { // 判断是否为最后一个属性,若不是则后增加逗号

                sb.append(field[i].getName()).append("=?,");

            } else { // 若为最后一个属性则添加 where

                sb.append(field[i].getName()).append("=? where ");

            }

        }

        // 默认第一个属性为主键,切更改时通过第一个属性进行更改

        sb.append(field[0].getName() + "=?");

        String sql = sb.toString() + ";";

        Connection conn = getConnection();// 获取连接对象

        PreparedStatement ps = null;

        try {

            ps = conn.prepareStatement(sql);

            for (int i = 1; i < field.length; i++) {

                field[i].setAccessible(true);// 设置可以访问私有属性

                ps.setObject(i, field[i].get(obj));// 对预编译的SQL语句中的 ? 进行赋值

            }

            field[0].setAccessible(true);

            ps.setObject(field.length, field[0].get(obj));

            ps.execute();// 执行sql语句

        } catch (Exception e) {

            e.printStackTrace();

        } finally {

            close(null, ps, conn);// 关闭连接数据

        }

    }

    public static void close(ResultSet rs, PreparedStatement ps, Connection conn) {

        try {

            if (rs != null)

                rs.close();

            if (ps != null)

                ps.close();

            if (conn != null)

                conn.close();

        } catch (SQLException e) {

            e.printStackTrace();

        }

    }

    public Object selectById(Class c, int id) {

        String sql = "select * from " + c.getSimpleName() + " where id=" + id;

        Field[] field = c.getDeclaredFields();

        Connection conn = getConnection();

        PreparedStatement ps = null;

        ResultSet rs = null;

        Object obj = null;

        try {

            ps = conn.prepareStatement(sql);

            rs = ps.executeQuery();

            obj = c.newInstance();

            while (rs.next()) {

                for (int i = 0; i < field.length; i++) {

                    field[i].setAccessible(true);

                    field[i].set(obj, rs.getObject(field[i].getName()));

                }

            }

        } catch (Exception e) {

            e.printStackTrace();

        } finally {

            close(rs, ps, conn);

        }

        return obj;

    }

}

十一、JDBC基础编程练习 

1、JDBC更新员工密码

 

package step1;

import java.sql.*;

public class UpdatePass {
   // 修改数据
   public static void updateDB() {

      /********* Begin *********/

      // 第一步:加载驱动
      try{
            Class.forName("com.mysql.jdbc.Driver");
        }catch(Exception e){
            e.printStackTrace();
        }
      

      // 第二步:建立连接, "root"和"123123"是针对MySQL设置了用户名(root)和密码(123123)的情况
      // 127.0.0.1:3306是mysql服务器地址及端口   数据库编码格式设置为utf-8
        // 第三步:建立statement对象
        // 第四步:修改数据
        // 第五步:关闭statement对象和连接对象
      Connection conn = null;
        PreparedStatement ps = null;
        try{
            String url = "jdbc:mysql://127.0.0.1:3306/tsgc?useUnicode=true&characterEncoding=utf8";
            String root = "root";
            String password="123123";
            conn = DriverManager.getConnection(url,root,password);

            String sql = "update employee set password='hello' where sex='女'";
            ps = conn.prepareStatement(sql);
            ps.execute();
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            try{
                ps.close();
                conn.close();
            }catch(Exception e){
                e.printStackTrace();
            }
        }
      /********* End *********/
   }

}

2、JDBC查询员工信息

package step1;

import java.sql.*;

public class QueryPass {
   
   // 查询数据代码不用上实验报告
   public static void queryDB() {
      
      /********* Begin *********/

      // 第一步:加载驱动
        // 第二步:建立连接, "root"和"123123"是针对MySQL设置了用户名(root)和密码(123123)的情况
        // 127.0.0.1:3306是mysql服务器地址及端口   数据库编码格式设置为utf-8
        // 第三步:建立statement对象
        // 第四步:查询数据
        // 第五步:关闭statement对象和连接对象
      Connection conn = null;
        PreparedStatement ps = null;
        try{
            Class.forName("com.mysql.jdbc.Driver");
            String url = "jdbc:mysql://127.0.0.1:3306/tsgc?useUnicode=true&characterEncoding=utf-8";
            String user = "root";
            String pass = "123123";
            conn = DriverManager.getConnection(url,user,pass);
            String sql = "select * from employee";
            ps = conn.prepareStatement(sql);
            ResultSet rs = ps.executeQuery();
            while(rs.next()){
                String no = rs.getString(1);
                String name = rs.getString(2);
                Object password = rs.getString(3);
                Object sex = rs.getString(4);
                double salary = rs.getDouble(5);
                System.out.println("no:"+no+"\tname:"+name+"\tpassword:"+password+"\tsex:"+sex+"\tsalary:"+salary);
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            try{
                ps.close();
                conn.close();
            }catch(Exception e){
                e.printStackTrace();
            }
        }
      /********* End *********/
   }
}

 

到此,此阶段的编程题便以结束,感谢各位读者的阅读,需要自取吧! 

你可能感兴趣的:(头歌实践题,java,开发语言)