然后就是建立数据库连接,使用Connection 新建连接,然后执行你的sql语句查询出需要的数据,下面是两个方法: public PageModel findAllUser(int pageNo,int pageSize){String sql = "select * from user where user_name <>'root' order by user_name" +"limit" + (pageNo - 1) * pageSize + "," + pageSizePageModel pageModel =nullConnection conn =nullStatement stmt =nullResultSet rs = nulltry{conn = DB.getConn()stmt = conn.createStatement()rs = stmt.executeQuery(sql)List user_List = new ArrayList()while(rs.next()){User user = new User()user.setUser_name(rs.getString("user_name"))user.setUser_password(rs.getString("user_password"))user.setUser_tel(rs.getString("user_tel"))user.setUser_email(rs.getString("user_email"))user.setUser_createDate(rs.getTimestamp("user_createdate"))user_List.add(user)}//取得所有记录int totalRecords = getTotalRecords(conn)pageModel = new PageModel()pageModel.setPageSize(pageSize)pageModel.setList(user_List)pageModel.setTotalRecord(totalRecords)}catch(SQLException e){e.printStackTrace()}finally{DB.close(rs)DB.close(stmt)DB.close(conn)}return pageModel} /** * 取得所有记录 * @param conn * @return 所有记录totalRecords */public int getTotalRecords(Connection conn){String sql = "select count(*) from user where user_name <>'root' "int totalRecords = 0Statement stmt = nullResultSet rs = nulltry{conn = DB.getConn()stmt = conn.createStatement()rs = stmt.executeQuery(sql)if(rs.next()){totalRecords = rs.getInt(1)}}catch(SQLException e){e.printStackTrace()}finally{DB.close(rs)DB.close(stmt)DB.close(conn)}return totalRecords}
php链接mysql必备条件:已安装mysql数据库;
检查php环境是否已开启mysql扩展(一般情况下是开启的);
检查方法:a.使用phpinfo()函数,看有没有mysql项;b.打开php.ini文件,检查php_mysql.dll前分号是否已取掉。
php链接代码如下:
<?php
//设置编码格式
header("Content-type:text/htmlcharset=utf-8")
//定义数据库主机地址
$host="localhost"
//定义mysql数据库登录用户名
$user="root"
//定义mysql数据库登录密码
$pwd=""
//链接数据库
$conn = mysql_connect($host,$user,$pwd)
//对连接进行判断
if(!$conn){
die("数据库连接失败!".mysql_errno())
}else{
echo "数据库连接成功!"
}
?>
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)