First, install MySQL and create the appropriate database and insert the information you want to manipulate (as shown in)
Second, load MySQL driver in MyEclipse
1) Right mouse button Item--"Build Path"--"Add Libraries ..."-select "User Library" and click "Next", as shown in the following image:
Finally, the information that appears at the project will indicate that the MySQL database was loaded successfully.
Third, enter in the servlet file that you created
1 PackageCom.servlet.datalink;2 3 Importjava.io.IOException;4 ImportJava.io.PrintWriter;5 Importjava.sql.Connection;6 ImportJava.sql.DriverManager;7 ImportJava.sql.ResultSet;8 Importjava.sql.Statement;9 Ten Importjavax.servlet.ServletException; One ImportJavax.servlet.http.HttpServlet; A Importjavax.servlet.http.HttpServletRequest; - ImportJavax.servlet.http.HttpServletResponse; - the Public classDatalinkextendsHttpServlet { - - Public voiddoget (httpservletrequest request, httpservletresponse response) - + throwsservletexception, IOException { - //Setting the context type +Response.setcontenttype ("Text/html;charset=utf-8"); A //set up unified document encoding atRequest.setcharacterencoding ("UTF-8"); -PrintWriter out =Response.getwriter (); - //create the appropriate variable and assign a value of NULL -Connection conn =NULL; -Statement stmt =NULL; -ResultSet rs =NULL; in - //through exception handling operations to Try{ + //load MySQL database driver -Class.forName ("Com.mysql.jdbc.Driver"); the //connecting to a database *conn = Drivermanager.getconnection ("Jdbc:mysql://localhost:3306/jifang", "root", "admin123456"); $ //To create a connection statePanax Notoginsengstmt =conn.createstatement (); - //working with a database thers = Stmt.executequery ("SELECT * from User"); + //Output HTML Information AOUT.PRINTLN ("); the //using a while loop to output information from a database + while(Rs.next ()) { -Out.println (rs.getstring ("id") + "<br/>"); $Out.println (rs.getstring ("username") + "<br/>"); $Out.println (rs.getstring ("password") + "<br/>"); - } -}Catch(Exception e) { the e.printstacktrace (); -}finally{Wuyi //Close the data source the } - Wu } - Public voidDoPost (httpservletrequest request, httpservletresponse response) About throwsservletexception, IOException { $ This. Doget (request, response); - } - -}
Iv. publish the project in Tomcat and test it with a browser
1) Publish the project in MyEclipse
2) Enter the URL path in the browser to display the results as follows
Note: This article for My learning experience, the above operations can be implemented.
Servlet connection to MySQL database