问题:
不同用户数据使用相同的数据库操作。
解决:
将操作的代码单独进行封装。
优点:
避免代码的冗余。
public class StudentDaoImpl {
public int updateSname(String newName) throws ClassNotFoundException, SQLException{
//1 加载驱动
Class.forName("oracle.jdbc.driver.OracleDriver");
//2 创建数据库连接对象
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@192.168.0.101:1521:XE","scott", "bjsxt");
conn.setAutoCommit(false);
//3 创建sql命令对象
Statement stmt = conn.createStatement();
//4 创建sql命令
String sql="update student set sname='"+newName+"' where snum=12";
//5 执行sql命令
try{
int i = stmt.executeUpdate(sql);
conn.commit();
return i;
}catch(Exception e){
conn.rollback();
}
//6 关闭资源
stmt.close();
conn.close();
return -1;
}
}
import com.bjsxt.daolmpl.StudentDaoImpl;
public class TestUpd {
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("昵称修改失败。");
}
}
}