从java到JDBC学习笔记

java编写代码入门

1. 简介

  • JDK : Java SE Development Kit Java开发工具

2.第一段代码

main快捷键 msvm加回车

控制台输出 sout+回车

删除一行 Ctrl+y

复制一行 Ctrl+d

空构造器 alt+insert

撤销快捷键 Ctrl+Z

首先输入psvm创建主程序,我们的代码在这里边编写。再输入sout创建输出模块,输出我们的hello java

3.简单基础

1.变量

2.循环

3.分支

4.数组

5.类和对象

1.创建类
2.构造器
3.封装 继承
4.方法重写

4.对比c++语法

不同c++java
主函数int mainpsvm
输出coutsout
数组int arr[]int[] arr
函数voidpublic static void
浮点3.143.14F
长整型..............L
创建类person p()
person p = new person()
继承:public personextends person
虚函数,重写virtual名字一样即可
基类指针取地址直接相等

java异常

Java异常处理是通过使用trycatchfinally, 和throw关键字来实现的。

  1. try

        将可能抛出异常的代码放在try块中。

  1. catch

        当try块中的代码抛出异常时,catch块捕获这个异常并处理。可以有多个catch块来捕获不同类型的异常。

  1. finally(可选):

        无论是否捕获或处理异常,finally块中的代码都会执行。通常用于关闭资源等清理操作。

  1. throw关键字:  

        用途throw关键字用于手动抛出一个异常实例。它通常用在方法体内,用来抛出一个具体的异常对象。

        语法throw后面跟着一个异常对象的实例。这个异常对象可以是Java标准库中的异常类型,也可以是自定义的异常类型。

public class ExceptionExample {
    public static void main(String[] args) {
        try {
            // 尝试执行的代码,可能会抛出异常
            int result = 10 / 0;
        } catch (ArithmeticException e) {
            // 处理特定类型的异常
            System.out.println("发生算术异常: " + e.getMessage());
        } catch (Exception e) {
            // 处理其他类型的异常
            System.out.println("发生异常: " + e.getMessage());
        } finally {
            // 无论是否发生异常,都会执行的代码
            System.out.println("finally块总是被执行。");
        }
        
        // 手动抛出异常
        try {
            throw new Exception("手动抛出的异常");
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}

集合

类似c++的stl

Java集合框架提供了一套性能优良、使用方便的接口和类,主要分为两大部分:Collection接口及其实现类和Map接口及其实现类。这些集合类存储的都是对象的引用。

Collection接口

Collection接口是最基本的集合接口,它有以下几个主要子接口:

  • List接口:一个有序的集合,可以包含重复的元素。主要实现类有ArrayListLinkedListVectorList接口的特点是可以精确控制每个元素插入的位置,可以通过索引来访问元素。

  • Set接口:一个不允许有重复元素的集合。主要实现类有HashSetLinkedHashSetTreeSetSet是通过元素的值来确定元素是否相同的,不像List那样通过元素的索引位置。

  • Queue接口:一种用于在处理前保持元素的集合。主要实现类有LinkedListPriorityQueue等。Queue接口支持常规队列的操作,如插入、移除和检查队列的头部元素。

Map接口

Map接口不是Collection的子接口,但它也是集合框架的一部分。Map存储键值对,每个键映射到一个值。

  • HashMap:存储键值对的数据结构,允许使用null值和null键。它不保证映射的顺序。

  • TreeMap:基于红黑树的NavigableMap实现。根据其键的自然顺序或者创建时所提供的Comparator进行排序。

  • LinkedHashMap:类似于HashMap,但它维护着一个运行于所有条目的双重链接列表。此链接列表定义了迭代顺序,通常是插入顺序。

  • Hashtable:和HashMap类似,但它是同步的。不允许null键或null值。

使用场景

  • List:当需要有序集合,可以包含重复元素时使用。
  • Set:当需要唯一元素集合,不允许重复时使用。
  • Queue:当需要支持元素的添加和按一定规则(如FIFO)移除时使用。
  • Map:当需要存储键值对,通过键快速检索数据时使用。

Java集合框架通过提供这些接口和类,极大地简化了集合的处理。

集合例子1

public class book {
    private int bno;
    private  String bname;
    private  String bauthor;

    public book(int bno, String bname, String bauthor) {
        this.bno = bno;
        this.bname = bname;
        this.bauthor = bauthor;
    }

    public book() {
        bno = 0;
        bname = "0";
        bauthor = "0";

    }

    public String getBauthor() {
        return bauthor;
    }

    public void setBauthor(String bauthor) {
        this.bauthor = bauthor;
    }

    public String getBname() {
        return bname;
    }

    public void setBname(String bname) {
        this.bname = bname;
    }

    public int getBno() {
        return bno;
    }

    public void setBno(int bno) {
        this.bno = bno;
    }
}
public class test {
    public static void main(String[] args) {
        ArrayList<book> list = new ArrayList();
        while (true) {//打印菜单
            System.out.println("------欢迎来到书城------");
            System.out.println("1.展示书籍");
            System.out.println("2.上新书籍");
            System.out.println("3.下架书籍");
            System.out.println("4.退出应用");
            //借助scanner类 扫描类
            Scanner sc = new Scanner(System.in);
            System.out.println("请录入你想要执行的功能的序号");
            int choice = sc.nextInt();
            if (choice == 1) {
                System.out.println("展示书籍功能");
                for (int i = 0; i < list.size(); ++i){
                    book b = (book) (list.get(i));
                    System.out.println(b.getBno() + "--" + b.getBname() + "--" + b.getBauthor());
                }
            } else if (choice == 2) {
                System.out.println("上新书籍功能");
                System.out.println("输入编号");
                int bno = sc.nextInt();
                System.out.println("输入书名");
                String bname = sc.next();
                System.out.println("输入作者");
                String bauthor = sc.next();
                book b = new book();
                b.setBno(bno);
                b.setBname(bname);
                b.setBauthor(bauthor);
                list.add(b);
            } else if (choice == 3) {
                System.out.println("下架书籍功能");
                System.out.println("输入下架书籍编号");
                int delete = sc.nextInt();
                for (int i = 0; i < list.size(); ++i){
                    book b = (book) (list.get(i));
                    if (b.getBno() == delete){
                        list.remove(b);
                        System.out.println("书籍下架成功");
                        break;
                    }
                }
            } else if (choice == 4) {
                System.out.println("退出应用功能");
                break;
            }
        }
    }
}

IO流

字节流
  • 输入流InputStream是所有字节输入流的抽象类,常用的实现类有FileInputStream(读取文件数据)、BufferedInputStream(提供缓冲区,提高读取效率)等。
  • 输出流OutputStream是所有字节输出流的抽象类,常用的实现类有FileOutputStream(写数据到文件)、BufferedOutputStream(提供缓冲区,提高写入效率)等。
字符流
  • 输入流Reader是所有字符输入流的抽象类,常用的实现类有FileReader(读取文件中的文本数据)、BufferedReader(提供缓冲区,支持按行读取,提高读取效率)等。
  • 输出流Writer是所有字符输出流的抽象类,常用的实现类有FileWriter(写文本数据到文件)、BufferedWriter(提供缓冲区,提高写入效率)等
输入流输出流

输入流和输出流是IO操作的基本概念。输入流用于从源读取数据,输出流用于向目标写数据。

  • 输入流:用于读取数据,数据源可以是文件、网络连接、内存区域等。
  • 输出流:用于写数据,目标可以是文件、网络连接、内存区域等

io例子 

public class test {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        Scanner sc = new Scanner(System.in);
        File f = new File("C:\\Users\\57746\\Desktop\\out.txt");
        ArrayList<book> list = new ArrayList();
        while (true) {//打印菜单

            System.out.println("------欢迎来到书城------");
            System.out.println("1.展示书籍");
            System.out.println("2.上新书籍");
            System.out.println("3.下架书籍");
            System.out.println("4.退出应用");
            //借助scanner类 扫描类
            System.out.println("请录入你想要执行的功能的序号");
            int choice = sc.nextInt();
            if (choice == 1) {
                System.out.println("展示书籍功能");

                if (f.exists() == true)
                {
                    FileInputStream fis = new FileInputStream(f);
                    ObjectInputStream ois = new ObjectInputStream(fis);
                    list = (ArrayList<book>) ois.readObject();
                    //读取集合
                    for (book b : list){
                        System.out.println(b.getBno() + "--" + b.getBname() + "--" + b.getBauthor());
                    }
                }
                else {
                    System.out.println("还未有新书籍");
                }
            } else if (choice == 2) {
                System.out.println("上新书籍功能");
                System.out.println("输入编号");
                int bno = sc.nextInt();
                System.out.println("输入书名");
                String bname = sc.next();
                System.out.println("输入作者");
                String bauthor = sc.next();
                book b = new book(bno,bname,bauthor);
                list.add(b);
                //管道
                FileOutputStream fos = new FileOutputStream(f);
                ObjectOutputStream oos = new ObjectOutputStream(fos);//序列化
                //写出
                oos.writeObject(list);
                oos.close();
                fos.close();
            } else if (choice == 3) {
                System.out.println("下架书籍功能");
                System.out.println("输入下架书籍编号");
                boolean found = false;
                int delete = sc.nextInt();
                for (int i = 0; i < list.size(); ++i){
                    book b = (book) (list.get(i));
                    if (b.getBno() == delete){
                        list.remove(b);
                        System.out.println("书籍下架成功");
                        found = true;
                        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(f))) {
                            oos.writeObject(list);
                        } catch (IOException e) {
                            System.out.println("更新书籍列表失败:" + e.getMessage());
                        }
                        break;
                    }
                }
            } else if (choice == 4) {
                System.out.println("退出应用功能");
                break;
            }
        }
    }
}

多线程

继承Thread类和实现Runnable接口。以下是这两种方式的基本用法

1. 继承Thread

继承Thread类是创建线程的一种简单方式。你需要做的是创建一个新类,该类继承自Thread类,然后覆盖run方法。run方法的方法体就是线程执行的代码。创建这个类的实例并调用其start方法来启动线程。

2. 实现Runnable接口

实现Runnable接口是创建线程的另一种方式。这种方式更加灵活,因为Java不支持多重继承,如果你的类已经继承了另一个类,就不能再继承Thread类了。在这种情况下,你可以让你的类实现Runnable接口。

网络编程

在cmd输入ipconfig获取ip

套接字

  • 套接字是网络通信的端点。每个套接字都绑定到一个特定的端口号和IP地址上。
  • 在Java中,Socket类代表客户端套接字,而ServerSocket类代表服务器套接字。

客户端套接字

  • 客户端创建一个Socket实例,指定服务器的IP地址和端口号来建立连接。
  • 通过套接字的输入输出流进行数据的发送和接收。

服务器套接字

  • 服务器创建一个ServerSocket实例,指定一个端口号,并监听该端口的连接请求。
  • ServerSocket接受到一个连接请求时,它会创建一个新的Socket实例来与客户端进行通信

XML

基础

<!-- 这是注释格式 -->
<!-- version版本号
encoding编码消息
有且只有一个根元素:students
子元素:写里面student
子子元素:name,age,score
1 2为属性值,必须加""
-->

<students>
    <student id="1">
        <name>missno</name>
        <age>19</age>
        <sez>男</sez>
        <score>100</score>
    </student>
    <student id="2">
        <name>mt</name>
        <age>19</age>
        <sez>女</sez>
        <score>920</score>
    </student>
</students>

注解

  • 内置注解:Java提供了一些预定义的注解,如@Override@author@version等。
  • 元注解:用于注解其他注解的注解。Java中的元注解包括@Target@Retention@Inherited@Documented@Repeatable
  • 自定义注解:用户可以定义自己的注解来满足特定需求。

MySQL

使用图形客户端navicat连接MySQL

SQL

操作数据库的语言

步骤

1.新建数据库

2.新建查询

3.创建表SQL

4.ctrl+s保存到查询中

创建表
create table t_book(
	id int,
	name varchar(30),
	author varchar(10), 
	price double
)

点击运行已选择的 

ctrl+s保存到查询中

select * from t_book;选中点击运行已选择的 为查询操作

--加上空格为注释
增删改查
增
向t_book表中插入一条新记录:

INSERT INTO t_book (id, name, author, price) VALUES (1, '书名', '作者', 100.00);

-----------------------

删
从t_book表中删除一条记录,这里以id作为删除条件:

DELETE FROM t_book WHERE id = 1;

------------------------

改
更新t_book表中的一条记录,这里以id作为更新条件:

UPDATE t_book SET name = '新书名', author = '新作者', price = 120.00 WHERE id = 1;

------------------------

查
查询t_book表中的所有记录:

SELECT * FROM t_book;

-----------------------



-- 查询全部数据
select * from t_book;

-- 增加
insert into t_book (id,name,author,price) values(1,'项目','hj', 66.6);
insert into t_book (id,name,author,price) values(2,'活着','余华', 100);

-- 删除
delete from t_book where id=1;

-- 修改
update t_book set price=36.6 where id=2;

-- 查看
select name,author from t_book; -- 看部分数据
select * from t_book where price > 40; -- 限制查看价格
where用法

比较操作符:可以使用比较操作符,如=、<、>、<=、>=、<>(不等于)。
SELECT * FROM t_book WHERE price > 50;

逻辑操作符:可以使用逻辑操作符AND、OR和NOT来组合多个条件。
SELECT * FROM t_book WHERE price >= 50 AND author = 'hj';

IN操作符:用于指定某个字段的值匹配列表中任意一个值。
SELECT * FROM t_book WHERE id IN (1, 2, 3);

LIKE操作符:用于模糊匹配,通常与通配符一起使用
SELECT * FROM t_book WHERE name LIKE '%项目%';

BETWEEN操作符:用于匹配一个范围内的值。
SELECT * FROM t_book WHERE price BETWEEN 50 AND 100;

IS NULL操作符:用于检查字段值是否为NULL。
SELECT * FROM t_book WHERE author IS NULL;

JDBC

java-数据库连接 让java代码能跟数据库里的资料连接

首先安装驱动mysql-connector-java-8.0.11.jar 然后放进包里运行

增删

import java.sql.*;

public class test2 {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        //加载驱动
        Class.forName("com.mysql.cj.jdbc.Driver");

        //获取连接
        String url = "jdbc:mysql://127.0.0.1:3306/test1?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true";
        String username = "root";//用户名
        String password = "root";//密码
        Connection conn = DriverManager.getConnection(url, username, password);

        //创建会话
        Statement sta = conn.createStatement();
        //发送sql
        ResultSet rs = sta.executeQuery("select * from t_book");//rs为结果集合-结果集 可以用where限制

        //处理结果
        while (rs.next()) {
            System.out.println(rs.getInt("id") + "---" + rs.getString("name") + "---" + rs.getString("author") + "---" + rs.getDouble("price"));
        }

        //关闭数据库资源

        sta.close();
        conn.close();
    }
}


DriverManager.getConnection获取连接
conn.createStatement();创建对话

public class test2 {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        //加载驱动
        Class.forName("com.mysql.cj.jdbc.Driver");

        //获取连接
        String url = "jdbc:mysql://127.0.0.1:3306/test1?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true";
        String username = "root";//用户名
        String password = "root";//密码
        Connection conn = DriverManager.getConnection(url, username, password);

        //创建会话
        Statement sta = conn.createStatement();
        //发送sql
        ResultSet rs = sta.executeQuery("select * from t_book");//rs为结果集合-结果集 可以用where限制

        //处理结果
        while (rs.next()) {
            System.out.println(rs.getInt("id") + "---" + rs.getString("name") + "---" + rs.getString("author") + "---" + rs.getDouble("price"));
        }

        //关闭数据库资源

        sta.close();
        conn.close();
    }
}

数据库例子

book的定义和上文一致

import java.sql.*;
import java.util.ArrayList;
import java.util.Scanner;

public class test {
    //  编号 名称 作者
    public static class 数据库书城 {
        public static void main(String[] args) throws SQLException, ClassNotFoundException {
            ArrayList<book> list = new ArrayList();
            while (true) {//打印菜单
                System.out.println("------欢迎来到书城------");
                System.out.println("1.根据书籍编号查询书籍消息");
                System.out.println("2.查询所有书籍的消息");
                System.out.println("3.下架指定编号的书籍");
                System.out.println("4.退出应用");
                //借助scanner类 扫描类
                Scanner sc = new Scanner(System.in);
                System.out.println("请录入你想要执行的功能的序号");
                int choice = sc.nextInt();
                if (choice == 1)
                {
                    //录入编号
                    System.out.println("录入要查询的书籍编号");
                    int ino = sc.nextInt();
                    //根据编号查询相应的书籍
                    book b = findBookByBno(ino);
                    if (b == null)
                    {
                        System.out.println("书籍未查询到");
                    }
                    else
                    {
                        System.out.println(b.getBname());
                    }
                }
                else if (choice == 2)
                {
                    findBook();
                }
                else if (choice == 3)
                {
                    System.out.println("输入要删除的书籍的编号");
                    int ino = sc.nextInt();
                    int i = deleteBookByBno(ino);
                    if (i <= 0)
                    {
                        System.out.println("删除失败");
                    }
                    else
                    {
                        System.out.println("删除成功");
                    }
                }
                else if (choice == 4)
                {
                    System.out.println("退出应用功能");
                    break;
                }
            }
        }
    }
    //根据编号查询相应的书籍
    public static book findBookByBno(int bno) throws ClassNotFoundException, SQLException {
        book b = null;

        //加载驱动
        Class.forName("com.mysql.cj.jdbc.Driver");

        //获取连接
        String url = "jdbc:mysql://127.0.0.1:3306/test1?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true";
        String username = "root";//用户名
        String password = "root";//密码
        Connection conn = DriverManager.getConnection(url, username, password);

        //创建会话
        Statement sta = conn.createStatement();

        //发送sql
        ResultSet rs = sta.executeQuery("select * from t_book where id = " + bno);//rs为结果集合-结果集 可以用where限制

        //处理结果
        if (rs.next()) {
            b = new book();
            int id = rs.getInt("id");
            String name = rs.getString("name");
            String author = rs.getString("author");
            double price = rs.getDouble("price");
            b.setBno(id);
            b.setBname(name);
            b.setBauthor(author);
            b.setPrice(price);
        }

        //关闭数据库资源

        sta.close();
        conn.close();
        return b;
    }
    public static void findBook() throws ClassNotFoundException, SQLException {
        book b = null;

        //加载驱动
        Class.forName("com.mysql.cj.jdbc.Driver");

        //获取连接
        String url = "jdbc:mysql://127.0.0.1:3306/test1?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true";
        String username = "root";//用户名
        String password = "root";//密码
        Connection conn = DriverManager.getConnection(url, username, password);

        //创建会话
        Statement sta = conn.createStatement();

        //发送sql
        ResultSet rs = sta.executeQuery("select * from t_book");//rs为结果集合-结果集 可以用where限制

        //处理结果
        while (rs.next()) {
            b = new book();
            int id = rs.getInt("id");
            String name = rs.getString("name");
            String author = rs.getString("author");
            double price = rs.getDouble("price");
            b.setBno(id);
            b.setBname(name);
            b.setBauthor(author);
            b.setPrice(price);
            System.out.println(b.getBname());
        }

        //关闭数据库资源

        sta.close();
        conn.close();
    }
    //删除对应书籍
    public static int deleteBookByBno(int bno) throws ClassNotFoundException, SQLException {
        //加载驱动
        Class.forName("com.mysql.cj.jdbc.Driver");

        //获取连接
        String url = "jdbc:mysql://127.0.0.1:3306/test1?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true";
        String username = "root";//用户名
        String password = "root";//密码
        Connection conn = DriverManager.getConnection(url, username, password);

        //创建会话
        Statement sta = conn.createStatement();

        //发送sql
        int n = sta.executeUpdate("delete from t_book where id =" + bno);//rs为结果集合-结果集 可以用where限制

        //关闭数据库资源

        sta.close();
        conn.close();
        return n;
    }
}
  • 13
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值