Dao类实现数据库连接

javaweb实现Dao类连接数据库

话不多说,直接上代码

package com.Dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DBjdbc {
/**
 * @param args
 */
	
	private final String url="jdbc:mysql://localhost:3306/你的数据库名字";
	private final String name="root";
	private final String password="你的密码";
	private  Connection con;

public DBjdbc(){
	
	try {
		  //加载驱动程序;
		  Class.forName("com.mysql.jdbc.Driver");
		  //获得数据库连接;
		con=DriverManager.getConnection(url,name,password);
		  }catch (ClassNotFoundException|SQLException e) {
			// TODO: handle exception
			System.out.println("驱动加载失败");
		}
}


public  void close() {

	if (this.con!=null) {
		try {
			this.con.close();
		} catch (SQLException e) {
			// TODO: handle exception
			System.out.println("数据库关闭失败");
		}
	}
	
}

public Connection getConnection() {
	

	// TODO Auto-generated method stub
	return this.con;
}


}
package com.bean;

public class users {
private int id;
private String name;
private String password;
public int getId() {
	return id;
}


public void setId(int id) {
	this.id = id;
}


public String getName() {
	return name;
}


public void setName(String name) {
	this.name = name;
}


public String getPassword() {
	return password;
}


public void setPassword(String password) {
	this.password = password;
}

}

package com.Dao;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.bean.users;


public class updateing  {
   public void checkusers(){
	   String sql="select * from users";
	   DBjdbc con=new DBjdbc();
	   
	   PreparedStatement pSt;
	   try {
		   pSt=con.getConnection().prepareStatement(sql);
		   ResultSet rSet=pSt.executeQuery();
		   
		   while (rSet.next()) {
			int id=rSet.getInt("id");
			String name=rSet.getString("name");
			String password=rSet.getString("password");
			System.out.println("学生编号:"+id+ "学生姓名:"+name+"学生密码:"+password);
		}
		   
	} catch (SQLException e) {
		// TODO: handle exception
	}
	   
	   con.close();
	  
   }
public static void main(String[] args) {
	updateing dd=new updateing();
	dd.checkusers();
}
}

这特么真是美好的一天,记录一下这该死的代码,让我下次使用的时候能够。ctrl+A+C+V.

  • 0
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值