java mysql分层_java-数据库连接,分层实现增删改查测试

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();

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值