简体   繁体   中英

inserting new user object into JDBC through the servlet

Here is the code for my servlet which recieves username parameter from a registration form

String tusername=request.getParamater("un");

String dbURL="db.com";
String dbusername= "lc";
String dbpassword="lcpw";
Connection con=(Connection) DriverManager.getConnection(dbURL,dbusername,dbpassword);

Statement stmt= con.createStatement();

String query="SELECT * FROM users.username WHERE username=(tusername)";

ResultSet rs= stmt.executeQuery(query);

if(rs.next()==false){
  //create new userobject with value of tusername
 }

My question is how do I create a new user object with calue of tusername, would it be like so ?

if(rs.next()==false){
  Statement stmt=con.createStatament();

  String query="INSERT INTO user.username VALUE 'tusername'";
  ResultSet rs= stmt.updateQuery(query);

 }

I understand some of this might be archaic (such as not using a prepared statement) , I am just trying to better my understanding and I think I am having some small syntax issues, thanks :)

You should be using a NOT EXISTS query to do the insert, and also you should ideally be using a prepared statement:

String sql = "INSERT INTO user.username (username) ";
sql += "SELECT ? FROM dual WHERE NOT EXISTS (SELECT 1 FROM user.username WHERE username = ?)";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, tusername);
ps.setString(2, tusername);
int result = ps.executeUpdate();

if (result > 0) {
    System.out.println("Inserted new user " + tusername + " into username table";
}
else {
    System.out.println("User " + tusername + " already exists; no new record was inserted");
}

I don't know what your actual database is. The above should work out of the box for MySQL and Oracle. It might need to be modified slightly for other databases.

An alternative to the above query would be to just use your current insert, but make the username column a (unique) primary key. In that case, any attempt to insert a duplicate would fail at the database level, probably resulting in an exception in your Java code. This would also be a more database agnostic approach.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM