目录
4、DataOutputStream和DataInputStream
5、BufferedInputStream和BufferedOutputStream
十三、Java中的集合框架
1、Java中集合框架的概述
数组长度固定,集合长度可变。
Java集合框架体系结构:
1)Collection接口:
子接口
List接口 序列(排列有序可重复)List常用的实现类ArrayList数组序列、
Queue接口 队列(排列有序可重复)LinkedList链表是List接口和Queue接口的实现类、
Set接口 集(排列无序不可重复)Set实现类HashSet哈希集
2)Map接口
Map也有众多子接口,最常用的是它的实现类HashMap哈希表
<Key,Value>映射是Entry类的实例,Entry类是Map的一个内部类,翻译成键值对。Key和Value可以是任意类型的对象
2、Collection接口、List接口简介
对象存入集合都变成Object类型,取出时需要类型转换。
List有add方法(两种)、addAll方法(两种)增加元素
get方法取元素
set方法修改元素
remove(对象、位置)、removeAll(集合)删除元素
例:
Course类:
public class Course {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Course(){}
public Course(int id,String name){
this.id=id;
this.name=name;
}
}
ListTest类:
import java.util.*;
public class ListTest {
public List coursesToSelect;
public ListTest(){
this.coursesToSelect=new ArrayList();
}
public void testAdd(){
Course cr1=new Course(1,"数据结构");
coursesToSelect.add(cr1);
Course temp=(Course)coursesToSelect.get(0);
System.out.println("添加了课程"+temp.getId()+":"+temp.getName());
Course cr2=new Course(2,"C语言");
coursesToSelect.add(0,cr2);
Course temp2=(Course)coursesToSelect.get(0);
System.out.println("添加了课程"+temp2.getId()+":"+temp2.getName());
/*以下方法会抛出数组下标越界异常
* Course cr3=new Course(3,"test");
coursesToSelect.add(3,cr2);*/
Course[] course={new Course(3,"离散数学"),new Course(4,"高数")};
coursesToSelect.addAll(Arrays.asList(course));
Course temp3=(Course)coursesToSelect.get(2);
Course temp4=(Course)coursesToSelect.get(3);
System.out.println("添加了课程"+temp3.getId()+":"+temp3.getName()+"\n"+temp4.getId()+":"+temp4.getName());
Course[] course2={new Course(5,"线性代数"),new Course(6,"大学英语")};
coursesToSelect.addAll(2,Arrays.asList(course2));
Course temp5=(Course)coursesToSelect.get(2);
Course temp6=(Course)coursesToSelect.get(3);
System.out.println("添加了课程"+temp5.getId()+":"+temp5.getName()+"\n"+temp6.getId()+":"+temp6.getName());
}
public void testGet(){
int size=coursesToSelect.size();
for(int i=0;i<size;i++){
Course cr=(Course)coursesToSelect.get(i);
System.out.println("*课程:"+cr.getId()+":"+cr.getName());
}
}
public void testIterator(){
Iterator it=coursesToSelect.iterator();
System.out.println("===遍历课程(迭代器):===");
while(it.hasNext()){
Course cr=(Course)it.next();
System.out.println(cr.getId()+":"+cr.getName());
}
}
public void testForEach(){
System.out.println("===遍历课程(foreach):===");
for(Object obj:coursesToSelect){
Course cr=(Course)obj;
System.out.println(cr.getId()+":"+cr.getName());
}
}
//修改List中的元素
public void testModify(){
coursesToSelect.set(5, new Course(4,"高等数学"));
}
//删除List中的元素
public void testRemove(){
//1、Course cr=(Course) coursesToSelect.get(4);
//System.out.println(cr.getId()+cr.getName()+"即将被删除");
//coursesToSelect.remove(cr);
//System.out.println("4位置上的元素即将被删除");
//2、coursesToSelect.remove(4);
System.out.println("\n4位置和5位置上的元素即将被删除");
Course[] courses={(Course)coursesToSelect.get(4),(Course)coursesToSelect.get(5)};
coursesToSelect.removeAll(Arrays.asList(courses));
System.out.println("成功删除课程!");
testForEach();
}
public static void main(String[] args) {
ListTest lt=new ListTest();
lt.testAdd();
lt.testGet();
lt.testIterator();
lt.testModify();
lt.testForEach();
lt.testRemove();
}
}
3、泛型
集合中的元素,可以是任意类型的对象(对象的引用)。如果把某个对象放入集合,则会忽略他的类型,而把他当做Object处理。
泛型则是规定了某个集合只可以存放特定类型的对象。会在编译期间进行类型检查,可以直接按指定类型获取集合元素。
例:
ChildCourse类:
public class ChildCourse extends Course{}
TestGeneric类:
import java.util.ArrayList;
import java.util.List;
public class TestGeneric {
//带有泛型Course的List类型属性
private List<Course> courses;
//构造方法
public TestGeneric(){
this.courses=new ArrayList<Course>();
}
//测试添加
public void testAdd(){
Course cr1=new Course(1,"大学语文");
courses.add(cr1);
//泛型集合中不能添加泛型规定的类型及其子类型以外的对象,否则会报错。
//courses.add("sdfd");
Course cr2=new Course(2,"Java基础");
courses.add(cr2);
}
//遍历
public void testForeach(){
//不再是Object类型
for(Course cr :courses){
System.out.println(cr.getId()+":"+cr.getName());
}
}
public void testChild(){
ChildCourse ccr=new ChildCourse();
ccr.setId(3);
ccr.setName("子类型课程对象实例");
courses.add(ccr);
}
public void testBasicType(){
//泛型是Integer,不是int
List<Integer> list=new ArrayList<Integer>();
list.add(1);
System.out.println("基本类型必须使用包装类作为泛型!"+list.get(0));
}
public static void main(String[] args) {
TestGeneric tg=new TestGeneric();
tg.testAdd();
tg.testChild();
tg.testForeach();
tg.testBasicType();
}
}
4、Set
Student类:
import java.util.*;
public class Student {
private int id;
private String name;
private Set<Course> courses;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<Course> getCourses() {
return courses;
}
public void setCourses(Set<Course> courses) {
this.courses = courses;
}
public Student(int id,String name){
this.id=id;
this.name=name;
this.courses=new HashSet<Course>();
}
}
SetTest类:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class SetTest {
private List<Course> coursesToSelect;
private SetTest(){
this.coursesToSelect=new ArrayList<Course>();
}
public void testAdd(){
Course cr1=new Course(1,"数据结构");
coursesToSelect.add(cr1);
Course cr2=new Course(2,"C语言");
coursesToSelect.add(0,cr2);
Course[] course={new Course(3,"离散数学"),new Course(4,"高数")};
coursesToSelect.addAll(Arrays.asList(course));
Course[] course2={new Course(5,"线性代数"),new Course(6,"大学英语")};
coursesToSelect.addAll(Arrays.asList(course2));
}
public void testForEach(){
System.out.println("===遍历课程(foreach):===");
for(Object obj:coursesToSelect){
Course cr=(Course)obj;
System.out.println(cr.getId()+":"+cr.getName());
}
}
//只有foreach和iterator,没有get方法
public void testForeachSet(Student stu){
System.out.println("共选择了"+stu.getCourses().size()+"门课。");
for(Course cr:stu.getCourses()){
System.out.println("学生选择了课程"+cr.getId()+":"+cr.getName());
}
}
public static void main(String[] args) {
SetTest st=new SetTest();
st.testAdd();
st.testForEach();
Student stu=new Student(1,"小明");
System.out.println("\n欢迎学生"+stu.getName()+"选课!");
//接收从键盘输入的课程id
Scanner sc=new Scanner(System.in);
for (int i = 0; i < 3; i++) {
System.out.println("请输入课程id:");
int courseId=sc.nextInt();
for(Course cr:st.coursesToSelect){
if(cr.getId()==courseId){
stu.getCourses().add(cr);
}
}
}
st.testForeachSet(stu);
}
}
十四、Java中的集合框架(二)
1、map
键(key)不可以重复,值(value)可以。
Map支持泛型,形式如:Map<K,V>
put(k,v)方法添加,remove(k)方法删除
keySet()返回key值的集合,values()返回value值的集合,entrySet键值对的集合。
例:
MapTest类:
import java.util.*;
public class MapTest {
private Map<Integer,Student> students;
public MapTest(){
this.students=new HashMap<Integer,Student>();
}
/*添加:
* 输入学生ID,判断是否被占用,若未被占用,则输入姓名,创建新学生对象,并且添加到students中
*/
public void testPut(){
Scanner sc=new Scanner(System.in);
int i=0;
while(i<3){
System.out.print("请输入学生ID:");
int ID=0;
if(sc.hasNextInt())
ID=sc.nextInt();
//get方法判断是否存在key值为ID的键值对,存在返回value值,不存在返回空对象
Student st=students.get(ID);
if(st==null){
System.out.print("请输入学生姓名:");
String name=sc.next();
Student newStudent=new Student(ID,name);
students.put(ID, newStudent);
System.out.println("成功添加学生:"+students.get(ID).getName());
i++;
}else{
System.out.println("该学生ID已经存在!");
}
}
}
//删除
public void testRemove(){
Scanner sc=new Scanner(System.in);
while(true){
System.out.print("\n请输入要删除的学生ID:");
int stuId=0;
if(sc.hasNextInt())
stuId=sc.nextInt();
Student st=students.get(stuId);
if(st==null){
System.out.println("输入的ID不存在");
}
else{
students.remove(stuId);
System.out.println("已成功删除"+st.getName());
break;
}
}
}
//修改
public void testModify(){
System.out.print("\n请输入要修改的学生ID:");
Scanner sc=new Scanner(System.in);
while(true){
int stuId=0;
if(sc.hasNextInt())
stuId=sc.nextInt();
Student st=students.get(stuId);
if(st==null){
System.out.println("输入的学生ID不存在,请重新输入!");
}
else{
System.out.println("当前学生ID对应的学生姓名为:"+st.getName());
System.out.print("请重新输入学生姓名:");
String stuName=sc.next();
students.put(stuId,new Student(stuId,stuName));
System.out.println("修改成功!");
break;
}
}
}
public void testKeySet(){
Set<Integer> keySet=students.keySet();
System.out.println("\n共有"+students.size()+"个学生。");
for(Integer stuId:keySet){
Student stu=students.get(stuId);
if(stu!=null)
System.out.println("学生:"+stu.getName());
}
}
//通过entrySet来遍历Map
public void testEntrySet(){
Set<Entry<Integer,Student>> entrySet=students.entrySet();
for(Entry<Integer,Student> entry:entrySet){
System.out.println("取得键:"+entry.getKey());
System.out.println("对应的值为:"+entry.getValue().getName());
}
}
public static void main(String[] args) {
MapTest mt=new MapTest();
mt.testPut();
mt.testKeySet();
mt.testRemove();
mt.testEntrySet();
mt.testModify();
mt.testEntrySet();
}
}
十五、Java中的集合框架(三)
1、List中是否存在某门课程
List的contains方法调用equals(obj)方法
Course类:
@Override
public boolean equals(Object obj){
//1、所指向的是否是同一个对象,即所指内存地址是否相等
if(this==obj)
return true;
//2、当前对象不可能为null,如果为null,则不能调用equals方法,否则抛出NullPointerException异常
if(obj==null)
return false;
//3、
if(!(obj instanceof Course))
return false;
Course course=(Course)obj;
//4、判断类的成员是否对应相等
if(this.getName()==null){
if(course.getName()==null)
return true;
else
return false;
}else{
if(this.getName().equals(course.getName()))
return true;
else
return false;
}
}
SetTest类:
public void testListContains(){
Course course=coursesToSelect.get(0);
System.out.println("课程名称:"+course.getName());
System.out.println("备选课程中是否包含该课程:"+coursesToSelect.contains(course));
//创建一个新的课程对象,ID和名称与course对象完全一样
Course course2=new Course(course.getId(),course.getName());
System.out.println("课程名称:"+course2.getName());
System.out.println("备选课程中是否包含该课程:"+coursesToSelect.contains(course2));
//用户输入课程名称
System.out.println("请输入课程名称:");
String name=sc.next();
Course course3=new Course();
course3.setName(name);
System.out.println("备选课程中是否包含该课程:"+coursesToSelect.contains(course3));
}
2、Set中是否存在某门课程
Set的contains方法先调用hashCode()方法返回哈希码,如果哈希码的值相等,再调用equals方法判断是否相等。只有两个方法返回的值都相等,才认定hashSet包含某个元素。
Course类:重写hashCode方法和equals方法,myEclipse自动生成
SetTest类:
public void testSetContains(){
System.out.println("请输入学生选择的课程名称:");
String name=sc.next();
Course course3=new Course();
course3.setName(name);
System.out.println("学生已选课程中是否包含该课程:"+stu.getCourses().contains(course3));
}
3、获取List中课程的位置
List的indexOf方法返回索引的位置。
if(coursesToSelect.contains(course3))
System.out.println(course3.getName()+"的索引位置为:"+coursesToSelect.indexOf(course3));
4、Map中是否包含指定的key和value
Map中的containsValue方法需要调用每个Value值的equals方法,匹配成功返回结果为true
Student类:重写equals方法
MapTest类:
public void testContainsKeyOrValue(){
System.out.println("请输入要查询的学生ID:");
Scanner sc=new Scanner(System.in);
int id=0;
if(sc.hasNextInt())
id=sc.nextInt();
System.out.println("学生ID"+id+"在学生映射表中是否存在:"+students.containsKey(id));
if(students.containsKey(id))
System.out.println("对应的学生为:"+students.get(id).getName());
System.out.println("请输入要查询的学生姓名:");
String name=sc.next();
Student st=new Student(0,name);
if(students.containsValue(st))
System.out.println("在学生映射表中存在学生"+name);
else
System.out.println("不存在该学生");
}
5、Collections工具类
java.util.Collections,定义的静态方法主要操作Collections。
sort()方法
CollectionTest类:
public class CollectionTest {
//通过Collections.sort()方法,对Integer泛型的List进行排序
public void testSort1(){
List<Integer> integerList=new ArrayList<Integer>();
Random rm=new Random();
int k;
for (int i = 0; i < 10; i++) {
do{
k=rm.nextInt(100);
}while(integerList.contains(k));
integerList.add(k);
}
System.out.println("------排序前------");
for(Integer i:integerList)
System.out.print(i+" ");
Collections.sort(integerList);
System.out.println("\n------排序后------");
for(Integer i:integerList)
System.out.print(i+" ");
}
//通过Collections.sort()方法,对String泛型的List进行排序
public void testSort2(){
List<String> stringList=new ArrayList<String>();
stringList.add("microsoft");
stringList.add("google");
stringList.add("lenovo");
System.out.println("******排序前******");
for(String s:stringList)
System.out.print(s+" ");
Collections.sort(stringList);
System.out.println("\n******排序后******");
//排列顺序:数字 大写字母 小写字母
for(String s:stringList)
System.out.print(s+" ");
}
public void testSort3(){
List<Student> studentList=new ArrayList<Student>();
Random r=new Random();
r.nextInt(100);
studentList.add(new Student(23,"Tom"));
studentList.add(new Student(123,"Jam"));
studentList.add(new Student(122,"Susan"));
System.out.println("排序前:");
for(Student s:studentList)
System.out.print(s.getId()+":"+s.getName()+"\t");
Collections.sort(studentList);
System.out.println("\n排序后:");
for(Student s:studentList)
System.out.print(s.getId()+":"+s.getName()+"\t");
Collections.sort(studentList, new StudentComparator());
System.out.println("\n按照姓名排序后:");
for(Student s:studentList)
System.out.print(s.getId()+":"+s.getName()+"\t");
}
public static void main(String[] args) {
CollectionTest ct=new CollectionTest();
/*ct.testSort1();
ct.testSort2();*/
ct.testSort3();
}
}
Student类:
public int compareTo(Student o) {
// TODO Auto-generated method stub
return new Integer(this.id).compareTo(o.id);
}
StudentComparator类:
public class StudentComparator implements Comparator<Student> {
public int compare(Student o1, Student o2) {
// TODO Auto-generated method stub
return o1.getName().compareTo(o2.getName());
}
}
6、Comparable接口和Comparator接口
Comparable默认比较规则
Comparator临时比较规则
Comparable接口;其实现类需实现compareTo()方法,返回正数表示大,负数表示小,0表示相等。
Comparator接口:其实现类需要实现compare()方法
十六、文件传输基础——Java IO流
1、java.io.File类用于表示文件(目录)
File类只用于表示文件(目录)的信息(名称、大小等),不能用于文件内容的访问。
public class FileDemo {
public static void main(String[] args) {
File file=new File("D:\\MyProject\\File");
if(!file.exists())
file.mkdir();
else
file.delete();
//是否是一个目录,如果不是目录或目录不存在返回false
System.out.println(file.isDirectory());
//是否是一个文件
System.out.println(file.isFile());
File file2=new File("D:\\MyProject\\日记1.txt");
//或File file2=new File("D:\\MyProject","日记1.txt");
if(!file2.exists())
try {
file2.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
else
file.delete();
System.out.println(file);//打印file.toString()内容,打印目录
System.out.println(file.getName());//打印目录或文件名
System.out.println(file.getParent());//访问父目录
}
}
补:FIleUtils类:https://www.cnblogs.com/my-blogs-for-everone/p/8029846.html
2、RandomAccessFile类的操作
RandomAccessFile提供对文件内容的访问,即可以读文件,也可以写文件。RandomAccessFile支持随机访问文件,可以访问文件的任意位置。
打开文件:有两种模式“rw(读写)”、“r(只读)”
RandomAccessFile raf=new RandomAccessFile(file,”rw”);
文件指针,打开文件时指针在开头pointer=0;
写方法:
raf.write(int),只写一个字节Byte(8位),同时指针指向下一个位置,准备再次写入。
读方法:
int b=raf.read(),读一个字节
文件读写完成后一定要关闭
例:
public class RafDemo {
public static void main(String[] args) throws IOException{
File demo=new File("demo");//没有写绝对路径,就是相对路径,在项目目录下
if(!demo.exists())
demo.mkdir();
File file=new File(demo,"raf.dat");
if(!file.exists())
file.createNewFile();
RandomAccessFile raf=new RandomAccessFile(file,"rw");
//指针的位置
raf.write('A');
System.out.println(raf.getFilePointer());
int i=0x7fffffff;
raf.writeInt(i);
System.out.println(raf.getFilePointer());
String s="中";
byte[] b=s.getBytes("gbk");
raf.write(b);
System.out.println(raf.length());
//读文件
raf.seek(0);
byte[] b1=new byte[(int)raf.length()];//raf.length()返回的是long
raf.read(b1);
System.out.println(Arrays.toString(b1));
raf.close();
}
}
3、字节流(FileInputStream和FileOutputStream)
InputStream、OutputStream类抽象了应用程序读取和写出数据的方式。
EOF结束,-1
输入流的基本方法:
int b=in.read()//读取一个字节无符号填充到int低8位
in.read(byte[] buf)//读取数据填充到字节数组buf
in.read(byte[] buf,int start,int size)
输出流的基本方法:
out.write(int b)//写出一个byte到流,b的低8位
out.write(byte[] buf)//将buf字节数组都写入到流
out.write(byte[] buf,int start,int size)
FileInputStream具体实现了在文件上读取数据
例:
public static void printHex(String fileName) throws IOException{
FileInputStream in=new FileInputStream(fileName);
int b;
int i=1;
while((b=in.read())!=-1){
//单位数前面补0
if(b<=0xf)
System.out.println("0");
System.out.print(Integer.toHexString(b)+" ");
if(i++%10==0)
System.out.println();
}
in.close();
}
public static void printHexByByteArray(String fileName) throws IOException{
FileInputStream in=new FileInputStream(fileName);
byte[] b=new byte[20*1024];
//从in中批量读取字节,放入到b这个字节数组中,从第0个位置开始放,最多放b.length,返回的是读到的字节的个数
/*int bytes=in.read(b,0,b.length);
int j=1;
for (int i = 0; i < bytes; i++) {
if(b[i]<=0xf)
System.out.print("0");
System.out.print(Integer.toHexString(b[i])+" ");
if(j++%10==0)
System.out.println();
}*/
int bytes;
int j=1;
while((bytes=in.read(b,0,b.length))!=-1){
for (int i = 0; i < bytes; i++) {
System.out.print(Integer.toHexString(b[i] & 0xff)+" ");
if(j++%10==0)
System.out.println();
}
}
}
FileOutputStream实现向文件中写byte数据的方法
FileOutputStream fos = new FileOutputStream("demo/out.dat", true);
fos.write('A');
int a = 10;
fos.write(a >>> 24);
fos.write(a >>> 16);
fos.write(a >>> 8);
fos.write(a);
String s = "中国";
byte[] gbk = s.getBytes("gbk");
fos.write(gbk);
fos.close();
4、DataOutputStream和DataInputStream
对流功能的扩展,可以更加方便的读取int,long,字符等类型的数据
writeInt()/writeDouble()/writeUTF()
5、BufferedInputStream和BufferedOutputStream
这两个类为IO提供了带缓冲区的操作,一般打开文件进行写入或读取操作时,都会加上缓冲,这种模式提高了IO的性能。
FileOutputStream的write()方法相当于一滴一滴地把水转移出去
DataOutputStream的writeXXX()方法相当于一瓢一瓢把水转移出去
BufferedInputStream的write()方法相当于一瓢一瓢先放入桶中,再从桶中转移出去
6、字符流(InputStreamReader和OutputStreamWriter)
文本:Java中的文本(char)是16位无符号整数,是字符的unicode编码
文件:byte byte byte的数据序列
文本文件:是文本(char)序列按照某种编码方案(utf-8,utf-16be,gbk)序列化为byte的存储结构。
字符流:--》操作的是文本文本文件
字符的处理,一次处理一个字符
字符的底层仍然是基本的字节序列
字符流的基本实现:
InputStreamReader 完成byte流解析为char流,按照编码解析
OutputStreamWriter 提供char流到byte流,按照编码处理
public class IsrAndOswDemo {
public static void main(String[] args) throws IOException {
FileInputStream in=new FileInputStream("D:/MyProject/MyEclipseProject/test.txt");
InputStreamReader isr=new InputStreamReader(in);//默认项目的编码,操作的时候写文件本身的编码格式,例InputStreamReader isr=new InputStreamReader(in,"utf-8");
FileOutputStream out=new FileOutputStream("D:/MyProject/MyEclipseProject/test1.txt");
OutputStreamWriter osw=new OutputStreamWriter(out);
/* int c;
while((c=isr.read())!=-1){
System.out.print((char)c);
}*/
char[] buffer=new char[8*1024];
int c;
//返回读到字符的个数
while((c=isr.read(buffer,0,buffer.length))!=-1){
String s=new String(buffer,0,c);
System.out.print(s);
osw.write(buffer,0,c);
osw.flush();
}
isr.close();
osw.close();
}
}
7、FileReader/FileWriter
public class FrAndFwDemo {
public static void main(String[] args) throws IOException{
FileReader fr=new FileReader("D:\\MyProject\\MyEclipseProject\\test.txt");
FileWriter fw=new FileWriter("D:\\MyProject\\MyEclipseProject\\test1.txt",true);
char[] buffer =new char[2056];
int c;
while((c=fr.read(buffer,0,buffer.length))!=-1){
fw.write(buffer,0,c);
fw.flush();
}
fr.close();
fw.close();
}
}
8、字符流的过滤器
BufferedReader readLine一次读一行
BufferedWriter /PrintWriter 写一行
public class BrAndBwOrPwDemo {
public static void main(String[] args) throws IOException{
BufferedReader br=new BufferedReader(
new InputStreamReader(
new FileInputStream("D:\\MyProject\\MyEclipseProject\\test.txt")));
/*BufferedWriter bw=new BufferedWriter(
new OutputStreamWriter(
new FileOutputStream("D:\\MyProject\\MyEclipseProject\\test2.txt")));*/
PrintWriter pw=new PrintWriter("D:\\MyProject\\MyEclipseProject\\test3.txt");
String line;
while((line=br.readLine())!=null){
System.out.println(line);//一次读一行,不识别换行
/* bw.write(line);
bw.newLine();//换行
bw.flush();*/
pw.println(line);
pw.flush();
}
br.close();
/*bw.close();*/
}
}
补:数据库日期时间型
Date 1000年1月1号 – 9999年12月31号
DateTime 1000年1月1号00:00:00 – 9999年12月31号23:59:59
Timestamp 1970年1月1号0点 – 2037年
Time -8385959 – 8385959
十七、JDBC
1、在代码中使用DriverManager获得数据库连接:
导入jar文件步骤:https://www.cnblogs.com/town123/p/8336244.html
import java.sql.*;
public class DBUtil {
private static final String URL="jdbc:mysql://127.0.0.1:3306/test";//test是数据库名
private static final String USER="root";//用户名
private static final String PASSWORD="root";//密码
public static void main(String[] args) throws Exception{
//1、加载驱动程序
//反射,通过一个类名,反向的将这个类加载到环境中
Class.forName("com.mysql.jdbc.Driver");
//2、获得数据库连接
//jdbc提供了一个驱动类,drivermanager
Connection con=DriverManager.getConnection(URL,USER,PASSWORD);
//通过数据库的连接操作数据库,实现增删改查
Statement stmt=con.createStatement();
//stmt.execute(sql);//执行任何SQL语句,返回一个boolean值,使用executeUpdate和executeQuery更好
//stmt.executeUpdate(sql);//用于执行insert、update、delete语句,返回一个整数,指受影响的行数
//stmt.executeQuery(sql);//用于执行select语句,返回查询结果的ResultSet对象
ResultSet rs=stmt.executeQuery("select userName,sex from user");
while(rs.next()){
System.out.println(rs.getString("userName")+" "+rs.getString("sex"));
}
}
}
DataBaseExplorer连接数据库:https://jingyan.baidu.com/article/4e5b3e196758ad91901e24a0.html
2、MVC三层架构
View(视图层)
Control(控制层):数据流通过程
Model(模型层):1、数据库映射 2、抽象方法(C、R、U、D)
DB
从下往上写
例:
com.test.jdbc DBUtil类:
package com.test.jdbc;
import java.sql.*;
//获得数据库连接
public class DBUtil {
private static final String URL = "jdbc:mysql://127.0.0.1:3306/test";// test是数据库名
private static final String USER = "root";// 用户名
private static final String PASSWORD = "root";// 密码
private static Connection con = null;
// 静态块执行最早
static {
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(URL, USER, PASSWORD);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static Connection getConnection(){
return con;
}
}
com.test.jdbc.model User类:
package com.test.jdbc.model;
import java.util.Date;
public class User {
private Integer userId;
private String userName;
private String sex;
private Integer age;
private String phone;
private Date birthday;
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "User [userId=" + userId + ", userName=" + userName + ", sex="
+ sex + ", age=" + age + ", phone=" + phone + ", birthday="
+ birthday + "]";
}
}
com.test.jdbc.dao UserDao类:
package com.test.jdbc.dao;
import java.util.*;
import com.test.jdbc.DBUtil;
import com.test.jdbc.model.User;
import java.sql.*;
//C、R、U、D
public class UserDao {
public void addUser(User user) throws SQLException{
Connection con=DBUtil.getConnection();
//String sql="insert into user(userName,sex,age,phone,birthday) values(?,?,?,?,current_date())";
//current_date():mysql的日期函数,当前日期
String sql="insert into user(userName,sex,age,phone,birthday) values(?,?,?,?,?)";
PreparedStatement ptmt=con.prepareStatement(sql);
ptmt.setString(1, user.getUserName());
ptmt.setString(2, user.getSex());
ptmt.setInt(3, user.getAge());
ptmt.setString(4, user.getPhone());
//需要的是java.sql的Date,传进来的是java.util的Date
ptmt.setDate(5, new Date(user.getBirthday().getTime()));
ptmt.execute();
}
public void updateUser(User user) throws SQLException{
Connection con=DBUtil.getConnection();
String sql="update user set userName=?,sex=?,age=?,phone=?,birthday=? where userId=?";
PreparedStatement ptmt=con.prepareStatement(sql);
ptmt.setString(1, user.getUserName());
ptmt.setString(2, user.getSex());
ptmt.setInt(3, user.getAge());
ptmt.setString(4, user.getPhone());
//需要的是java.sql的Date,传进来的是java.util的Date
ptmt.setDate(5, new Date(user.getBirthday().getTime()));
ptmt.setInt(6, user.getUserId());
ptmt.execute();
}
public void delUser(Integer userId) throws SQLException{
Connection con=DBUtil.getConnection();
String sql="delete from user where userId=?";
PreparedStatement ptmt=con.prepareStatement(sql);
ptmt.setInt(1, userId);
ptmt.execute();
}
/* public List<User> query() throws SQLException{
Connection con=DBUtil.getConnection();
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select userName,sex from user");
List<User> users=new ArrayList<User>();
User user;
while (rs.next()) {
user=new User();
user.setUserName(rs.getString("userName"));
user.setSex((rs.getString("sex")));
users.add(user);
}
return users;
}*/
//查询多个
public List<User> query(String userName) throws SQLException{
Connection con=DBUtil.getConnection();
StringBuilder sb=new StringBuilder();
sb.append("select * from user ");
/*sb.append("where userName=?");*/
sb.append("where userName like ?");
PreparedStatement ptmt = con.prepareStatement(sb.toString());
/*ptmt.setString(1, userName);*/
ptmt.setString(1, "%"+userName+"%");
ResultSet rs = ptmt.executeQuery();
List<User> users=new ArrayList<User>();
User user;
while (rs.next()) {
user=new User();
user.setUserId(rs.getInt("userId"));
user.setUserName(rs.getString("userName"));
user.setSex(rs.getString("sex"));
user.setAge(rs.getInt("age"));
user.setPhone(rs.getString("phone"));
user.setBirthday(rs.getDate("birthday"));
users.add(user);
}
return users;
}
//查询条件多
public List<User> query(List<Map<String,Object>> params) throws SQLException{
Connection con=DBUtil.getConnection();
StringBuilder sb=new StringBuilder();
sb.append("select * from user where 1=1");
if(params!=null && params.size()>0){
for (int i = 0; i < params.size(); i++) {
Map<String,Object> map=params.get(i);
//查询什么,关系是什么,值是什么
sb.append(" and "+map.get("name")+" "+map.get("rela")+" "+map.get("value"));
}
}
System.out.println(sb.toString());
PreparedStatement ptmt = con.prepareStatement(sb.toString());
ResultSet rs = ptmt.executeQuery();
List<User> users=new ArrayList<User>();
User user;
while (rs.next()) {
user=new User();
user.setUserId(rs.getInt("userId"));
user.setUserName(rs.getString("userName"));
user.setSex(rs.getString("sex"));
user.setAge(rs.getInt("age"));
user.setPhone(rs.getString("phone"));
user.setBirthday(rs.getDate("birthday"));
users.add(user);
}
return users;
}
//查询单个
public User get(Integer userId) throws SQLException{
User user = null;
Connection con=DBUtil.getConnection();
String sql="select * from user where userId=?";
PreparedStatement ptmt=con.prepareStatement(sql);
ptmt.setInt(1, userId);
ResultSet rs=ptmt.executeQuery();
while(rs.next()){
user=new User();
user.setUserId(rs.getInt("userId"));
user.setUserName(rs.getString("userName"));
user.setSex(rs.getString("sex"));
user.setAge(rs.getInt("age"));
user.setPhone(rs.getString("phone"));
user.setBirthday(rs.getDate("birthday"));
}
return user;
}
}
com.test.jdbc.action UserAction类:
package com.test.jdbc.action;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import com.test.jdbc.dao.UserDao;
import com.test.jdbc.model.User;
//控制层,调用模型层的方法
public class UserAction {
public void add(User user) throws SQLException{
UserDao ua=new UserDao();
ua.addUser(user);
}
public void edit(User user) throws SQLException{
UserDao ua=new UserDao();
ua.updateUser(user);
}
public void del(Integer userId) throws SQLException{
UserDao ua=new UserDao();
ua.delUser(userId);
}
public User get(Integer userId) throws SQLException{
UserDao ua=new UserDao();
return ua.get(userId);
}
public List<User> query() throws SQLException{
UserDao ua=new UserDao();
return ua.query();
}
public List<User> query(List<Map<String,Object>> params) throws SQLException{
UserDao ua=new UserDao();
return ua.query(params);
}
}
com.test.jdbc.action UserActionTest类:
package com.test.jdbc.action;
import java.sql.SQLException;
import java.util.*;
import com.test.jdbc.model.User;
public class UserActionTest {
public static void main(String[] args) throws SQLException {
UserAction ua=new UserAction();
User u=new User();
u.setUserName("小枫");
u.setSex("女");
u.setAge(15);
u.setPhone("1667892345");
u.setBirthday(new Date());
u.setUserId(6);
//增加 不需要id
// ua.add(u);
//修改 需要正确的id
// ua.edit(u);
// ua.del(7);
//查询
/*User u1=ua.get(4);
System.out.println(u1);*/
/*List<User> result=ua.query();
for(User u:result){
System.out.println(u);
}*/
/*List<Map<String,Object>> params=new ArrayList<Map<String,Object>>();
Map<String,Object> map=new HashMap<String,Object>();
map.put("name", "userName");
map.put("rela", "like");
map.put("value", "'%小%'");
params.add(map);
map=new HashMap<String,Object>();
map.put("name", "birthday");
map.put("rela", ">");
map.put("value", "2019-10-1");
params.add(map);
List<User> users=ua.query(params);
for(User user:users)
System.out.println(user);*/
}
}