<%
String ID = request.getParameter("ID");
String password = request.getParameter("password");
String rpassword = request.getParameter("rpassword");
String name = request.getParameter("name");
String sex = request.getParameter("sex");
String year = request.getParameter("year");
if(year.length() ==1) year = "0"+year;
String mouth = request.getParameter("mouth");
if(mouth.length() == 1) mouth = "0"+mouth;
String day = request.getParameter("day");
if(day.length() == 1) day = "0"+day;
String date = year+"-"+mouth+"-"+day;
String description = request.getParameter("description");
Connection con = null;
PrepareStatement psm = null;
ResultSet rs = null;
try
{
Class.forName("com.mysql.jdbc.Driver").newInstance();
String url = "jdbc:mysql://localhost:3306/mydb";
con = DriverManager.getConnection(url,"root","000000");
psm = con.prepareStatement("insert into users values(?,?,?,?,?,?)");
psm.setString(1,ID);
psm.setString(2,password);
psm.setString(3,name);
psm.setString(4,sex);
psm.setLong(5,getDate(date));
psm.setString(6,description);
psm.executeUpdate();
session.setAttribute("user",ID);
response.sendRedirect("index.jsp");
}
catch(Exception e){
response.sendRedirect("register.jsp");
}
finally
{
if(rs!=null){
try{ rs.close();}catch(Exception e){e.printStackTrace();}
}
if(psm!=null){
try{ psm.close();}catch(Exception e){e.printStackTrace();}
}
if(con!=null){
try{ con.close();}catch(Exception e){e.printStackTrace();}
}
}
%>
我想在插入操作之前先判断要插入记录的用户名是否在数据库中已经存在了,怎么写呢,我是新手,还请高手多帮忙啊~
这样:
psm = con.prepareStatement("select * from users where username=?");
psm.setString(1,name);
rs = psm.executeQuery();
if(rs!=null){
out.println("该用户名已经被注册!");
response.sendRedirect("register.jsp");
}
else{
在这里写插入数据的语句
}
注意事项
访问数据库类文件写法
//根据传过来的用户名查询数据库中是否存在此用户
public String tblUserExist(String uName){
String username = "";
String sql="select uName from tbl_user where uName=?";
try {
pst = con.prepareStatement(sql);
pst.setString(1,uName);
ResultSet rst = pst.executeQuery();
if(rst.next()){
username=rst.getString(uName);
}
} catch (SQLException e)
{
e.printStackTrace();
}finally
{
this.closepst();//关闭pst对象
this.closecon();//关闭数据库对象
}
return username;
}