The code that writes the servlet today needs to be connected to the database, but due to the recent failure to write the database code, frequent errors, it is necessary to record, the next time this situation can be fixed in time
First steps required to connect to a database
1. Load the driver class by reflection
1 String className = "Com.mysql.jdbc.Driver";
2 class.forname (className);
2. Create a connection channel
1 String url = "Jdbc:mysql://localhost/dbjdbc"; 2 String dbuser = "root"; 3 String dbpassword = "123456"; 4 5 NULL ; 6 con = drivermanager.getconnection (URL, dbuser, Dbpassword);
3. Create statement
1 Statement Statement = null;
2 statement = Con.createstatement ();
4. Performing Database operations
ResultSet rs=NULL; RS= Statement.executequery ("Select password from db_users where username= '" +username+ "'");//indicates that the user existsif(Rs.next ()) {String PASSW=rs.getstring (1); if(passw.equals (password)) {//Get SessionHttpSession HS = Req.getsession (true); //Modify session existence timeHs.setmaxinactiveinterval (30); //Session Add Property PassHs.setattribute ("Pass", "OK"); Res.sendredirect ("Welcome?uname=" +username+ "&upassw=" +password+ "&sx=" +sex); } Else { //Description Password ErrorRes.sendredirect ("Login?info=error1"); }}Else { //indicates that the user name does not existRes.sendredirect ("Login?info=error1"); }
The other is the problem that was found in the servlet writing.
java.lang.ClassNotFoundException:com.mysql.jdbc.Driver (servlet link MySQL database failure workaround)
In the process of writing code to the Ecplipse to import the connection to MySQL jar package, but always reported that the database connection failed, unable to find the driver class, in fact, because the server to find driver class when not found, You can add jar packages to the Lib folder in the Tomcat installation directory once and for all, or you can add jar packages to Web-inf/lib in this project directory, but the latter will also need to copy the jar package from Lib to the appropriate Lib folder during deployment.
In addition, the packet java.sql.* in the connection database;
servlet connection to MySQL database