难点 statement 枚举类的应用

本文介绍了 Java 中用于执行 SQL 语句的三种 Statement 对象:Statement、PreparedStatement 和 CallableStatement 的区别及用途。此外,还解析了一个关于枚举 AccountType 的代码示例,详细解释了枚举在 Java 中的实现方式及其初始化过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.下面哪个不是标准Statement类?

正确答案: D   你的答案: A (错误)

Statement
PreparedStatement
CallableStatement
BatchedStatement

Statement 对象用于将 SQL 语句发送到数据库中。实际上有三种 Statement 对象,它们都作为在给定连接上执行 SQL 语句的包容器:Statement、PreparedStatement(它从 Statement 继承而来)和 CallableStatement(它从 PreparedStatement 继承而来)。它们都专用于发送特定类型的 SQL 语句: Statement 对象用于执行不带参数的简单 SQL 语句;PreparedStatement 对象用于执行带或不带 IN 参数的预编译 SQL 语句;CallableStatement 对象用于执行对数据库已存在的存储过程的调用。

Statement是sql语句的载体
Statement是标准的Statement类,通过字符串对sql语句进行拼接,但是它存在sql注入的危险
PreparedStatement对sql语句进行了预编译,可以防止SQL注入
CallableStatement用来调用存储过程的
BatchedStatement用于批量操作数据库,BatchedStatement不是标准的Statement类

2.what is the result of the following code?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
enumAccountType
{
    SAVING, FIXED, CURRENT;
    privateAccountType()
    {
        System.out.println(“It is a account type”);
    }
}
classEnumOne
{
    publicstatic void main(String[]args)
    {
        System.out.println(AccountType.FIXED);
    }
}
 
    

正确答案: C   你的答案: B (错误)

Compiles fine and output is prints”It is a account type”once followed by”FIXED”
Compiles fine and output is prints”It is a account type”twice followed by”FIXED”
Compiles fine and output is prints”It is a account type”thrice followed by”FIXED”
Compiles fine and output is prints”It is a account type”four times followed by”FIXED”
Compilation fails
枚举类在后台实现时,实际上是转化为一个继承了java.lang.Enum类的实体类,原先的枚举类型变成对应的实体类型,
上例中AccountType变成了个class AccountType,并且会生成一个新的构造函数,若原来有构造函数,则在此基础上
添加两个参数,生成新的构造函数,如上例子中:
1
privateAccountType(){ System.out.println(“It is a account type”); }
会变成:
1
2
privateAccountType(String s, inti){
    super(s,i); System.out.println(“It is a account type”); }
而在这个类中,会添加若干字段来代表具体的枚举类型:
1
2
3
publicstatic final AccountType SAVING;
publicstatic final AccountType FIXED;
publicstatic final AccountType CURRENT;

而且还会添加一段static代码段:
1
2
3
4
5
6
static{
    SAVING = newAccountType("SAVING"0);
    ...  CURRENT = newAccountType("CURRENT"0);
   $VALUES = newAccountType[]{
         SAVING, FIXED, CURRENT
    } }
以此来初始化枚举中的每个具体类型。(并将所有具体类型放到一个$VALUE数组中,以便用序号访问具体类型)
在初始化过程中new AccountType构造函数被调用了三次,所以Enum中定义的构造函数中的打印代码被执行了3遍。
怎么通过执行AccountType.FIXED这句到调用静态代码块的?这个其实是与java类中静态代码的初始化有关:类中的静态类型,
仅在程序中第一次被使用时才会被初始化,且只初始化一次。初始化过程中还会自动调用类中用static{ }括起来的代码。
因此static final的字段的初始化过程才可以写在static{ }中。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值