stmt.setInt(1, Integer.parseInt(input));
时间: 2024-05-20 08:12:07 浏览: 101
这段代码是用于设置 PreparedStatement 的参数值。其中,setInt() 方法用于设置参数的数据类型为整型,第一个参数表示参数的索引位置,第二个参数表示参数的值,这里是将字符串类型的 input 转换为整型。一般情况下,这个 PreparedStatement 对象会在执行 SQL 语句之前被创建,并通过设置参数值来填充 SQL 语句中的占位符,以便执行查询、更新或删除操作。
相关问题
<% //连接数据库 String driver = "com.mysql.jdbc.Driver"; String url = "jdbc:mysql://localhost:3306/votedb?serverTimezone=UTC&characterEncoding=UTF-8"; String username = "root"; String password = "123456"; Connection conn = null; Statement stmt = null; ResultSet rs = null; try { Class.forName(driver); conn = DriverManager.getConnection(url, username, password); stmt = conn.createStatement(); rs = stmt.executeQuery("SELECT * FROM vote"); while(rs.next()){ String title = rs.getString("title"); %> <input type="radio" name="option" value="<%=title%>"><%=title%><br> <% } } catch (Exception e) { e.printStackTrace(); } finally { //关闭连接 try { if (rs != null) { rs.close(); } if (stmt != null) { stmt.close(); } if (conn != null) { conn.close(); } } catch (SQLException e) { e.printStackTrace(); } } %> <a href="showVote.jsp">提交投票</a>选中后数据库数据变化
根据您的代码,您想要实现的功能是:在页面上展示投票选项列表(从数据库中查询出来),用户在选中一个选项后,点击“提交投票”按钮,将投票结果存储到数据库中。
您想要实现的选中后数据库数据变化,可能是指将用户的投票结果存储到数据库中。在提交投票的页面中,您可以编写一个表单,其中包含一个隐藏的投票ID字段和一个单选框选项,用户选中后提交表单。后台代码根据投票ID和选中的选项,将投票结果存储到数据库中。
这里提供一个简单的代码示例:
1. 提交投票页面(submitVote.jsp):
```html
<form action="voteHandler.jsp" method="post">
<% // 根据你的数据库结构修改以下代码
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/votedb?serverTimezone=UTC&characterEncoding=UTF-8";
String username = "root";
String password = "123456";
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName(driver);
conn = DriverManager.getConnection(url, username, password);
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT * FROM vote");
while(rs.next()){
int id = rs.getInt("id");
String title = rs.getString("title");
%>
<input type="radio" name="option" value="<%=id%>"><%=title%><br>
<% }
} catch (Exception e) {
e.printStackTrace();
}
finally {
//关闭连接
try {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
%>
<input type="hidden" name="voteId" value="<%=voteId%>">
<input type="submit" value="提交投票">
</form>
```
2. 处理投票请求(voteHandler.jsp):
```java
<% // 获取用户选择的选项和投票ID
String option = request.getParameter("option");
String voteId = request.getParameter("voteId");
// 根据你的数据库结构修改以下代码
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/votedb?serverTimezone=UTC&characterEncoding=UTF-8";
String username = "root";
String password = "123456";
Connection conn = null;
PreparedStatement pstmt = null;
try {
Class.forName(driver);
conn = DriverManager.getConnection(url, username, password);
pstmt = conn.prepareStatement("INSERT INTO vote_result(vote_id, option_id) VALUES (?, ?)");
pstmt.setInt(1, Integer.parseInt(voteId));
pstmt.setInt(2, Integer.parseInt(option));
pstmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
finally {
//关闭连接
try {
if (pstmt != null) {
pstmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
response.sendRedirect("voteResult.jsp?voteId=" + voteId); // 投票成功后跳转到投票结果页面
%>
```
3. 投票结果页面(voteResult.jsp):
```html
<% // 获取投票ID并查询投票选项和结果
String voteId = request.getParameter("voteId");
// 根据你的数据库结构修改以下代码
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/votedb?serverTimezone=UTC&characterEncoding=UTF-8";
String username = "root";
String password = "123456";
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName(driver);
conn = DriverManager.getConnection(url, username, password);
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT v.title, o.title AS option_title, COUNT(*) AS vote_count FROM vote v LEFT JOIN vote_option o ON v.id = o.vote_id LEFT JOIN vote_result r ON o.id = r.option_id WHERE v.id = " + voteId + " GROUP BY o.id");
while(rs.next()){
String title = rs.getString("title");
String optionTitle = rs.getString("option_title");
int voteCount = rs.getInt("vote_count");
%>
<p><%=optionTitle %>: <%=voteCount %> 票</p>
<%
}
} catch (Exception e) {
e.printStackTrace();
}
finally {
//关闭连接
try {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
%>
```
希望这个示例能够帮助您完成您的需求。
1.创建Person类,Person的属性有: Strng name 姓名 String sex 性别 Integer age 年龄, String idNo 身份证号 Boolean isMerried 是否已婚 请生成相应的getter、setter方法。请编写注解@Label,表示所注解对象的中文名称,请把@Label注解标注在Person类和Person的每个属性上面。请编写PersonInput类,负责提示录入人员的相关属性,提示必须是注解@Label所标注的中文名称。请编写PersonDisplay,负责显示人员信息,显示时的属性名称必须为注解@Label所标注的中文名称,PersonInput类与PersonDisplay类实现了共同的接口PersonAction,接口PersonAction有方法process,方法process的签名为:public Person process(Person person); 2.在第一题目的基础上,编写注解@Column,属性有Label 表示类的属性的显示名称,Nullable 表示是否允许属性值为空,MaxLength 表示文本属性的最大长度,MinLength表示文本属性的最小长度,MaxValue表示最大值,MinValue表示最小值,把注解@Column加在Person类的每个属性上,在输入Person时根据注解@Column的配置进行校验。第一题的@Label只标注在类上。根据注解生成Person类对应的数据库表创建语句,以及生成数据库表的删除、新增、修改SQL语句。 并利用JDBC,实现数据库操作。只生成第二题代码
先给出完整代码,再一步步解释。
```java
import java.lang.annotation.*;
import java.util.Scanner;
public class PersonInput implements PersonAction {
private static Scanner input = new Scanner(System.in);
@Override
public Person process(Person person) {
Class cls = person.getClass();
Field[] fields = cls.getDeclaredFields();
for (Field field : fields) {
boolean isAccess = field.isAccessible();
if (!isAccess) {
field.setAccessible(true);
}
Label label = field.getAnnotation(Label.class);
Column column = field.getAnnotation(Column.class);
if (label != null) {
System.out.print(label.value() + ": ");
}
if (column != null) {
String inputStr = input.nextLine();
if (!column.nullable() && (inputStr == null || inputStr.length() == 0)) {
System.out.println(column.label() + "不能为空");
inputStr = input.nextLine();
}
if (column.maxLength() > 0 && inputStr.length() > column.maxLength()) {
System.out.println(column.label() + "长度不能超过" + column.maxLength() + "个字符");
inputStr = input.nextLine();
}
if (column.minLength() > 0 && inputStr.length() < column.minLength()) {
System.out.println(column.label() + "长度不能少于" + column.minLength() + "个字符");
inputStr = input.nextLine();
}
if (column.maxValue() > Long.MIN_VALUE) {
long value = Long.parseLong(inputStr);
if (value > column.maxValue()) {
System.out.println(column.label() + "不能大于" + column.maxValue());
inputStr = input.nextLine();
}
}
if (column.minValue() < Long.MAX_VALUE) {
long value = Long.parseLong(inputStr);
if (value < column.minValue()) {
System.out.println(column.label() + "不能小于" + column.minValue());
inputStr = input.nextLine();
}
}
try {
if (field.getType() == String.class) {
field.set(person, inputStr);
} else if (field.getType() == Integer.class) {
int value = Integer.parseInt(inputStr);
field.set(person, value);
} else if (field.getType() == Long.class) {
long value = Long.parseLong(inputStr);
field.set(person, value);
} else if (field.getType() == Boolean.class) {
boolean value = Boolean.parseBoolean(inputStr);
field.set(person, value);
}
} catch (Exception e) {
e.printStackTrace();
}
}
if (!isAccess) {
field.setAccessible(false);
}
}
return person;
}
}
import java.lang.annotation.*;
public class PersonDisplay implements PersonAction {
@Override
public Person process(Person person) {
Class cls = person.getClass();
Field[] fields = cls.getDeclaredFields();
for (Field field : fields) {
boolean isAccess = field.isAccessible();
if (!isAccess) {
field.setAccessible(true);
}
Label label = field.getAnnotation(Label.class);
if (label != null) {
try {
System.out.println(label.value() + ": " + field.get(person));
} catch (Exception e) {
e.printStackTrace();
}
}
if (!isAccess) {
field.setAccessible(false);
}
}
return person;
}
}
@Target({ElementType.TYPE, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@interface Label {
String value();
}
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface Column {
String label();
boolean nullable() default true;
int maxLength() default 0;
int minLength() default 0;
long maxValue() default Long.MIN_VALUE;
long minValue() default Long.MAX_VALUE;
}
interface PersonAction {
Person process(Person person);
}
class Person {
@Label("姓名")
@Column(label = "姓名", nullable = false, maxLength = 32)
private String name;
@Label("性别")
@Column(label = "性别")
private String sex;
@Label("年龄")
@Column(label = "年龄", minValue = 0, maxValue = 200)
private Integer age;
@Label("身份证号")
@Column(label = "身份证号", maxLength = 18)
private String idNo;
@Label("是否已婚")
@Column(label = "是否已婚")
private Boolean isMarried;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
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 getIdNo() {
return idNo;
}
public void setIdNo(String idNo) {
this.idNo = idNo;
}
public Boolean getMarried() {
return isMarried;
}
public void setMarried(Boolean married) {
isMarried = married;
}
}
public class Main {
private static final String CREATE_TABLE_SQL = "CREATE TABLE `person` (\n" +
" `id` int(11) NOT NULL AUTO_INCREMENT,\n" +
" `name` varchar(32) NOT NULL,\n" +
" `sex` varchar(8) DEFAULT NULL,\n" +
" `age` int(11) DEFAULT NULL,\n" +
" `id_no` varchar(18) DEFAULT NULL,\n" +
" `married` tinyint(1) DEFAULT NULL,\n" +
" PRIMARY KEY (`id`)\n" +
") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;";
private static final String DROP_TABLE_SQL = "DROP TABLE IF EXISTS `person`;";
private static final String INSERT_SQL = "INSERT INTO `person` (`name`, `sex`, `age`, `id_no`, `married`) VALUES (?, ?, ?, ?, ?);";
private static final String UPDATE_SQL = "UPDATE `person` SET `name`=?,`sex`=?,`age`=?,`id_no`=?,`married`=? WHERE `id`=?;";
private static final String DELETE_SQL = "DELETE FROM `person` WHERE `id`=?;";
public static void main(String[] args) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8", "root", "123456");
Statement stmt = conn.createStatement();
stmt.executeUpdate(DROP_TABLE_SQL);
stmt.executeUpdate(CREATE_TABLE_SQL);
PersonInput input = new PersonInput();
PersonDisplay display = new PersonDisplay();
Person person = new Person();
input.process(person);
display.process(person);
ps = conn.prepareStatement(INSERT_SQL);
ps.setString(1, person.getName());
ps.setString(2, person.getSex());
ps.setInt(3, person.getAge());
ps.setString(4, person.getIdNo());
ps.setBoolean(5, person.getMarried());
ps.executeUpdate();
ps = conn.prepareStatement(UPDATE_SQL);
ps.setString(1, person.getName());
ps.setString(2, person.getSex());
ps.setInt(3, person.getAge());
ps.setString(4, person.getIdNo());
ps.setBoolean(5, person.getMarried());
ps.setInt(6, 1);
ps.executeUpdate();
ps = conn.prepareStatement(DELETE_SQL);
ps.setInt(1, 1);
ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (rs != null) {
rs.close();
}
if (ps != null) {
ps.close();
}
if (conn != null) {
conn.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
```
首先,我们定义了两个注解,@Label和@Column。其中,@Label是用来给类和属性添加中文名称的,@Column是用来给属性添加数据库字段的一些配置信息的。
```java
@Target({ElementType.TYPE, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@interface Label {
String value();
}
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface Column {
String label();
boolean nullable() default true;
int maxLength() default 0;
int minLength() default 0;
long maxValue() default Long.MIN_VALUE;
long minValue() default Long.MAX_VALUE;
}
```
然后,我们定义了一个Person类,它有姓名、性别、年龄、身份证号、是否已婚等属性,每个属性都添加了@Label和@Column注解。我们使用注解处理器,可以根据@Column注解的配置信息来进行输入校验,这样就可以避免输入错误的数据。同时,我们还定义了PersonInput和PersonDisplay两个类,它们都实现了PersonAction接口,分别用于输入和输出一个Person对象。
```java
class Person {
@Label("姓名")
@Column(label = "姓名", nullable = false, maxLength = 32)
private String name;
@Label("性别")
@Column(label = "性别")
private String sex;
@Label("年龄")
@Column(label = "年龄", minValue = 0, maxValue = 200)
private Integer age;
@Label("身份证号")
@Column(label = "身份证号", maxLength = 18)
private String idNo;
@Label("是否已婚")
@Column(label = "是否已婚")
private Boolean isMarried;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
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 getIdNo() {
return idNo;
}
public void setIdNo(String idNo) {
this.idNo = idNo;
}
public Boolean getMarried() {
return isMarried;
}
public void setMarried(Boolean married) {
isMarried = married;
}
}
interface PersonAction {
Person process(Person person);
}
public class PersonInput implements PersonAction {
@Override
public Person process(Person person) {
Class cls = person.getClass();
Field[] fields = cls.getDeclaredFields();
for (Field field : fields) {
boolean isAccess = field.isAccessible();
if (!isAccess) {
field.setAccessible(true);
}
Label label = field.getAnnotation(Label.class);
Column column = field.getAnnotation(Column.class);
if (label != null) {
System.out.print(label.value() + ": ");
}
if (column != null) {
String inputStr = input.nextLine();
if (!column.nullable() && (inputStr == null || inputStr.length() == 0)) {
System.out.println(column.label() + "不能为空");
inputStr = input.nextLine();
}
if (column.maxLength() > 0 && inputStr.length() > column.maxLength()) {
System.out.println(column.label() + "长度不能超过" + column.maxLength() + "个字符");
inputStr = input.nextLine();
}
if (column.minLength() > 0 && inputStr.length() < column.minLength()) {
System.out.println(column.label() + "长度不能少于" + column.minLength() + "个字符");
inputStr = input.nextLine();
}
if (column.maxValue() > Long.MIN_VALUE) {
long value = Long.parseLong(inputStr);
if (value > column.maxValue()) {
System.out.println(column.label() + "不能大于" + column.maxValue());
inputStr = input.nextLine();
}
}
if (column.minValue() < Long.MAX_VALUE) {
long value = Long.parseLong(inputStr);
if (value < column.minValue()) {
System.out.println(column.label() + "不能小于" + column.minValue());
inputStr = input.nextLine();
}
}
try {
if (field.getType() == String.class) {
field.set(person, inputStr);
} else if (field.getType() == Integer.class) {
int value = Integer.parseInt(inputStr);
field.set(person, value);
} else if (field.getType() == Long.class) {
long value = Long.parseLong(inputStr);
field.set(person, value);
} else if (field.getType() == Boolean.class) {
boolean value = Boolean.parseBoolean(inputStr);
field.set(person, value);
}
} catch (Exception e) {
e.printStackTrace();
}
}
if (!isAccess) {
field.setAccessible(false);
}
}
return person;
}
}
public class PersonDisplay implements PersonAction {
@Override
public Person process(Person person) {
Class cls = person.getClass();
Field[] fields = cls.getDeclaredFields();
for (Field field : fields) {
boolean isAccess = field.isAccessible();
if (!isAccess) {
field.setAccessible(true);
}
Label label = field.getAnnotation(Label.class);
if (label != null) {
try {
System.out.println(label.value() + ": " + field.get(person));
} catch (Exception e) {
e.printStackTrace();
}
}
if (!isAccess) {
field.setAccessible(false);
}
}
return person;
}
}
```
最后,我们在Main类中使用JDBC,将Person对象保存到数据库中。在保存之前,先执行了一次删除表和创建表的操作。
```java
public class Main {
private static final String CREATE_TABLE_SQL = "CREATE TABLE `person` (\n" +
" `id` int(11) NOT NULL AUTO_INCREMENT,\n" +
" `name` varchar(32) NOT NULL,\n" +
" `sex` varchar(8) DEFAULT NULL,\n" +
" `age` int(11) DEFAULT NULL,\n" +
" `id_no` varchar(18) DEFAULT NULL,\n" +
" `married` tinyint(1) DEFAULT NULL,\n" +
" PRIMARY KEY (`id`)\n" +
") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;";
private static final String DROP_TABLE_SQL = "DROP TABLE IF EXISTS `person`;";
private static final String INSERT_SQL = "INSERT INTO `person` (`name`, `sex`, `age`, `id_no`, `married`) VALUES (?, ?, ?, ?, ?);";
private static final String UPDATE_SQL = "UPDATE `person` SET `name`=?,`sex`=?,`age`=?,`id_no`=?,`married`=? WHERE `id`=?;";
private static final String DELETE_SQL = "DELETE FROM `person` WHERE `id`=?;";
public static void main(String[] args) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8", "root", "123456");
Statement stmt = conn.createStatement();
stmt.executeUpdate(DROP_TABLE_SQL);
stmt.executeUpdate(CREATE_TABLE_SQL);
PersonInput input = new PersonInput();
PersonDisplay display = new PersonDisplay();
Person person = new Person();
input.process(person);
display.process(person);
ps = conn.prepareStatement(INSERT_SQL);
ps.setString(1, person.getName());
ps.setString(2, person.getSex());
ps.setInt(3, person.getAge());
ps.setString(4, person.getIdNo());
ps.setBoolean(5, person.getMarried());
ps.executeUpdate();
ps = conn.prepareStatement(UPDATE_SQL);
ps.setString(1, person.getName());
ps.setString(2, person.getSex());
ps.setInt(3, person.getAge());
ps.setString(4, person.getIdNo());
ps.setBoolean(5, person.getMarried());
ps.setInt(6, 1);
ps.executeUpdate();
ps = conn.prepareStatement(DELETE_SQL);
ps.setInt(1, 1);
阅读全文