import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class Practise3 {
//更新
public void UpdatePet(){
Connection conn=null;
PreparedStatement pst=null;
String driver="jdbc:sqlserver://localhost:1433;DatabaseName=epet";
String sql="update dog set health=?,love=? where id=?";
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn=DriverManager.getConnection(driver,"zhou","123");
pst=conn.prepareStatement(sql);
pst.setInt(1, 3);
pst.setInt(2, 32);
pst.setInt(3, 5);
pst.executeUpdate();
System.out.println("更新成功");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally{
if(pst!=null){
try {
pst.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
//删除
public void delectPet(){
Connection conn=null;
PreparedStatement pstm=null;
String driver="jdbc:sqlserver://localhost:1433;DatabaseName=epet";
String sql="delete from dog where id=?";
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn=DriverManager.getConnection(driver,"zhou","123");
pstm=conn.prepareStatement(sql);
pstm.setInt(1, 6);
pstm.executeUpdate();
System.out.println("删除成功");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally{
if(pstm!=null){
try {
pstm.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
//插入
public void savePet(){
Connection conn=null;
PreparedStatement ptm=null;
String sql="insert into dog (name,health,love,strain) values(?,?,?,?)";
String driver="jdbc:sqlserver://localhost:1433;databasename=epet";
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn=DriverManager.getConnection(driver,"zhou","123");
ptm=conn.prepareStatement(sql);
ptm.setString(1, "彪子");
ptm.setInt(2, 38);
ptm.setInt(3, 38);
ptm.setString(4, "我很好");
int num=ptm.executeUpdate();
if(num>0){
System.out.println("插入成功");
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally{
if(ptm!=null){
try {
ptm.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}