Java连接MySQL的问题
首次使用Java连接MySQL做一个登录的功能 查询的user总是空 不知道为什么 求教这里是BaseDao
package dao;
import java.sql.*;
public class BaseDao {
private final static String DRIVER = "com.mysql.jdbc.Driver";
private final static String URL="jdbc:mysql://localhost:3306/user";
private final static String DBNAME = "root";
private final static String DBPASS = "sa";
/**
* 得 到数据库的链接
* @return
* @throws ClassNotFoundException
* @throws SQLException
*/
public Connection getConn()throws ClassNotFoundException ,SQLException
{
Class.forName(DRIVER); // 注册驱动
Connection conn = DriverManager.getConnection(URL, DBNAME, DBPASS) ; //
return conn; // 返回连接
}
/**
* 释放资源
* @param conn
* @param pstmt
* @param rs
*/
public void closeAll(Connection conn, PreparedStatement pstmt ,ResultSet rs)
{
if(rs!=null)
{
try{rs.close();}catch(SQLException e){}
}
if(pstmt!=null)
{
try{pstmt.close();}catch(SQLException e){}
}
if(conn!=null)
{
try{conn.close();}catch(SQLException e){}
}
}
}
这 里是查询数据库的方法
public class UserDaoImpl extends BaseDao implements UserDao {
private Connection conn = null;
private PreparedStatement pstmt = null;
private ResultSet rs = null;
private User user = null;
public User login(String userName) {
// TODO Auto-generated method stub
String sql ="select * from User where Name=?";
try {
conn = this .getConn();
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, userName);
rs = pstmt.executeQuery();
while(rs.next())
{
user = new User();
user.setId(rs.getInt("id"));
user.setName(rs.getString("Name"));
user.setPassword(rs.getString("Password"));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally{
this.closeAll(conn, pstmt, rs);
}
return user;
}
在 JSP页面中
<%
request.setCharacterEncoding("GBK");
String name = request.getParameter("userName");
String pwd = request.getParameter("pwd");
UserBiz userBiz = new UserBizImpl();
User user= userBiz.login(name);
System.out.println(user);
int num = userBiz.login(user.getId());
System.out.println(num);
if(num!=0 && user!=null && user.getPassword().equals(pwd))
{
response.sendRedirect("success.jsp");
}else
{
response.sendRedirect("error.jsp");
}
%>
[ 本帖最后由 游走之客 于 2010-4-19 21:13 编辑 ]