JDBC编程学习笔记

初识JDBC编程

JDBCUtils工具类

public class JDBCUtils{
	private static final String connectionurl="jdbc://localhost:3306/数据库名称?useUnicode=true&characterEncoding=UTF8&useSSL=false";
	private static final String username ="root";
	private static final String password = "root";
	public Connection getConnection(){
		Class.forName("com.mysql.jdbc.Driver");
		return DrvierManager.getConnection(connectionurl, username, password)
	}
	public void close(ResultSet rs ,PreparedStatement pstmt,Connection con){
		if(rs!=null)rs.close();
		if(pstmt!=null)pstmt.close();
		if(con!=null)con.close();

	}
}
//调用
public void select(){
		connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		con = JDBCUtils.getConnection();
		pstmt = con.prepareStatement("select * form user limit ?,? ");
		pstmt.setInt(1,(pagenum-1)*pagecount);
		pstmt.setInt(2,pagecount);
		rs = pstmt.executeQuery();
		whlie(rs.next()){
			System.out.println(rs.getInt("id")+rs.getString("username")+rs.getString("password"));
		}
		JDBCUtils.close( rs ,pstmt, con);
}

不使用工具类

public void select(){
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		//Class.forName("com.mysql.jdbc.Driver");
		String url="jdbc://localhost:3306/数据库名称?useUnicode=true&characterEncoding=UTF8&useSSL=false";
		String username = "root";
		String password = "root";
		con = DriverManager.getconnection(url,username,password);
		String sql = "select * form user limit ?,? ";//起始行,结束行;一般第一个参数为(page-1)*行数,第二个为行数
		pstmt = con.prepareStatement(sql);
		pstmt.setInt(1,(pagenum-1)*pagecount);
		pstmt.setInt(2,pagecount);
		rs = pstmt.executeQuery();
		whlie(rs.next()){
			System.out.println(rs.getInt("id")+rs.getString("username")+rs.getString("password"));
		}
		if(rs!=null)rs.close();
		if(pstmt!=null)pstmt.close();
		if(con!=null)con.close();

	}

更新操作

public void select(){
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		//Class.forName("com.mysql.jdbc.Driver");
		String url="jdbc://localhost:3306/数据库名称?useUnicode=true&characterEncoding=UTF8&useSSL=false";
		String username = "root";
		String password = "root";
		con = DriverManager.getconnection(url,username,password);
		String sql = "insert into user(username,password) values(?,?) ";
		pstmt = con.prepareStatement(sql);
		pstmt.setInt(1,username);
		pstmt.setInt(2,password);
		int rs = pstmt.executeUpdate();
		
		
		if(pstmt!=null)pstmt.close();
		if(con!=null)con.close();

	}

你可能感兴趣的:(学习,JDBC)