packagecom.zhidisoft.dao;importjava.sql.Connection;importjava.sql.DriverManager;importjava.sql.ResultSet;importjava.sql.SQLException;importjava.sql.Statement;importcom.zhidisoft.entity.Dog;//用来实现数据库的操作 连接、释放数据库 通用的增删改查
public classDatabaseAction {
Connection conn= null;//连接数据库
publicConnection getConnection(){
String url= "jdbc:mysql://127.0.0.1:3306/test?" + "user=root&password=root&useUnicode=true&characterEncoding=UTF8";try{
Class.forName("com.mysql.jdbc.Driver");//声明驱动的jar包
conn = DriverManager.getConnection(url);//按照url提供的路径连接服务器
} catch (ClassNotFoundException |SQLException e) {//TODO Auto-generated catch block
e.printStackTrace();
}//动态加载mysql驱动
returnconn;
}//向数据库插入信息
public intzhuce(Dog dog){
conn=this.getConnection();//调用连接数据库方法,连接服务器
String sql="insert into Dog()
values("+dog.getNumber()+",'"+dog.getName()+"','"+dog.getStrain()+"','"+dog.getSex()+"',"+dog.getAge()+",'"+dog.getMatters()+"')";
Statement st;int result=0;try{
st=conn.createStatement();
result=st.executeUpdate(sql);//执行sql语句,返回结果为int类型,受影响的行数
conn.close();//关闭数据库连接
} catch(SQLException e) {//TODO Auto-generated catch block
e.printStackTrace();
}returnresult;
}public int shanchu(intnumber){
conn=this.getConnection();
String sql= "delete from Dog where number = "+number;
Statement st;int result = 0;try{
st=conn.createStatement();
result=st.executeUpdate(sql);
conn.close();
}catch(SQLException e) {//TODO Auto-generated catch block
e.printStackTrace();
}returnresult;
}public intgenggai(String name,String matters){
conn=this.getConnection();
String sql= "update Dog set matters ='"+matters+"' where name = '"+name+"'";
Statement st;int result = 0;try{
st=conn.createStatement();
result=st.executeUpdate(sql);
conn.close();
}catch(SQLException e) {//TODO Auto-generated catch block
e.printStackTrace();
}returnresult;
}public voidchazhao(Dog dog){
conn=this.getConnection();
String sql= "select * from Dog";
Statement st;try{
st=conn.createStatement();
ResultSet rs=st.executeQuery(sql);while (rs.next()) {//遍历输出查询记录
System.out.println("编号:"+rs.getInt("number")+"\t姓名 "+rs.getString("name")+"\t品种:"+rs.getString("strain")+"\t性
别:"+rs.getString("sex")+"\t年龄:"+rs.getInt("age")+"\t病情:"+rs.getString("matters"));
}
conn.close();
}catch(SQLException e) {//TODO Auto-generated catch block
e.printStackTrace();
}
}
}