package jdbc.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class DbUtil {
//数据库地址
private static String dbUrl="jdbc:mysql://localhost:3306/mybatis_db";
//用户名
private static String dbUserName="root";
//密码
private static String dbPassword="#######################################################";
//驱动名称
private static String jdbcName="com.mysql.jdbc.Driver";
/**
* 获取数据库连接
* @return
* @throws Exception
*/
public Connection getCon()throws Exception{
Class.forName(jdbcName);
Connection con=DriverManager.getConnection(dbUrl, dbUserName,dbPassword);
return con;
}
/**
* 关闭连接
* @param con
* @throws Exception
*/
public void close(Statement stmt,Connection con)throws Exception{
if(stmt!=null){
stmt.close();
if(con!=null){
con.close();
}
}
}
}
package model;
/**
* 个人信息
* @author MC-DS
*
*/
public class Person {
private int id;
private String personName;
private int age;
public Person(int id, String personName, int age) {
super();
this.id = id;
this.personName = personName;
this.age = age;
}
public Person(String personName, int age) {
super();
this.personName = personName;
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPersonName() {
return personName;
}
public void setPersonName(String personName) {
this.personName = personName;
}
public Integer getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
package jdbc.chap03;
import java.sql.Connection;
import java.sql.Statement;
import jdbc.util.DbUtil;
import model.Person;
public class Demo03 {
private static DbUtil dbUtil=new DbUtil();
private static int update01(Person person)throws Exception{
Connection con=dbUtil.getCon();//获取连接
String sql="update t_student set name='"+person.getPersonName()+"',age="+person.getAge()+" where id="+person.getId()+"";
Statement stmt=con.createStatement();//创建Statement
int result=stmt.executeUpdate(sql);
dbUtil.close(stmt, con);//关闭Statement和连接
return result;
}
public static void main(String[] args) throws Exception {
Person person=new Person(7,"古天樂",37);
int result=update01(person);
if(result==1){
System.out.println("更新成功了!");
}else {
System.out.println("更新失败!");
}
}
}
更新成功了!