import java.sql.SQLException;
import java.util.Scanner;
import com.bjsxt.daoImpl.StudentDaoImpl;

/**

  • 需求:
  • 更新用户昵称,使用控制台获取新的用户昵称,跟新成功后提示更新成功.
  • 分析:
  • java+jdbc
  • 使用:
  • 创建java类
  • 创建main方法
  • 创建Scanner对象获取控制台数据
  • 使用JDBC将数据更新到数据库中
  • 提示更新成功
  • 问题:
  • 不同的用户数据使用相同的数据库操作.
  • 解决:
  • 将数据操作代码单独进行封装.
  • 优点:
  • 避免代码的冗余
  • 封装:
  • @author MyPC

*/
public class UpdateName {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//创建Scanner对象
Scanner sc=new Scanner(System.in);
System.out.println(“请输入新的昵称:”);
String newName=sc.nextLine();
//调用Dao层对数据库进行操作
StudentDaoImpl sd=new StudentDaoImpl();
int i=sd.updateSname(newName);
//判断
if(i>0){
System.out.println(“更改成功”);
}else{
System.out.println(“更改失败”);
}
}
}


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import com.bjsxt.pojo.Student;

public class StudentDaoImpl {
//查询所有学生信息
public ArrayList getStudentInfo() throws ClassNotFoundException, SQLException{
//声明List集合
ArrayList list=new ArrayList<>();
//加载驱动
Class.forName(“oracle.jdbc.driver.OracleDriver”);
//创建连接对象
Connection conn=DriverManager.getConnection(“jdbc:oracle:thin:@localhost:1521:orcl”,“scott”,“oracle”);
//创建sql命令对象
Statement stmt=conn.createStatement();
//创建Sql命令
String sql=“select * from student”;
//执行Sql命令
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
//创建学生对象
Student stu=new Student();
stu.setSnum(rs.getInt(“snum”));
stu.setSname(rs.getString(“sname”));
stu.setSage(rs.getInt(“sage”));
stu.setMoney(rs.getDouble(“money”));
//将对象存储到ArrayList中
list.add(stu);
}
return list;
}

//根据新的昵称修改用户昵称
public int updateSname(String newName) throws ClassNotFoundException, SQLException{
//加载驱动
Class.forName(“oracle.jdbc.driver.OracleDriver”);
//创建连接对象
Connection conn=DriverManager.getConnection(“jdbc:oracle:thin:@localhost:1521:orcl”, “scott”, “oracle”);
//设置事务手动提交
conn.setAutoCommit(false);
//创建sql命令对象
Statement stmt=conn.createStatement();
//创建sql命令
String sql=“update student set sname=’”+newName+"’ where snum=6";
//执行sql命令
int i=-1;
try {
i=stmt.executeUpdate(sql);
conn.commit();
} catch (Exception e) {
conn.rollback();
}
//关闭资源
stmt.close();
conn.close();
return i;
}
}