The first thing to do is import the jar package.
The rest is basically the code of the mold layout:
public class Main {//JDBC driver name and database urlstatic final String jdbc_driver = "Com.mysql.jdbc.Driver"; Static final String Db_url = "jdbc:mysql://localhost:3306/test";//port number, database name//database user name and password, you need to set static final Stri Ng USER = "root"; static final String PASS = "";p ublic static void Main (String args[]) {Connection conn = null; Statement stmt = null;try{//Register JDBC driver Class.forName ("Com.mysql.jdbc.Driver");//Open link System.out.println ("Connect database ..."); conn = (Connection) drivermanager.getconnection (db_url,user,pass);//Execute Query SYSTEM.OUT.PRINTLN ("Instantiate statement to ..."); stmt = (Statement) conn.createstatement (); String sql;sql = "INSERT into students VALUES (\" Li\ ", \" 1234\ ");//Insert Data stmt.executeupdate (SQL) into the database; sql =" Select Unmbe R, name from students "; ResultSet rs = stmt.executequery (sql);//Expand result set Database while (Rs.next ()) {//Retrieve string by field name = Rs.getstring ("name"); String id = rs.getstring ("Unmber");//Output Data System.out.print ("ID:" + ID); System.out.print (", Name:" + name); System.out.print ("\ n");} Close Rs.clos when finishedE (); Stmt.close (); Conn.close ();} catch (SQLException se) {//Handle JDBC error Se.printstacktrace ();} catch (Exception e) {//Handles Class.forName error E.printstacktrace ();} finally{//Close Resource try{if (stmt!=null) stmt.close (); catch (SQLException se2) {}//do nothing try{if (conn!=null) Conn.close ();} catch (SQLException se) {se.printstacktrace ();}} System.out.println ("goodbye!");}}
Servlet calls the database through Java
Basically the same as the Java direct call.
But one thing is important!!!!!!!!!!!
Never import a jar package into a Web project and report a ClassNotFound exception.
Delete the jar package and put it under Tomcat's lib.
public class Hello extends HttpServlet {private static final long Serialversionuid = 1l;//JDBC driver name and database Urlstatic F inal String jdbc_driver = "Com.mysql.jdbc.Driver"; Static final String db_url = "jdbc:mysql://localhost:3306/test";//the user name and password of the database needs to be static final string user = "root" according to its own settings; Static final String PASS = ""; /** * @see httpservlet#httpservlet () */public Hello () {super (); TODO auto-generated Constructor stub}/** * @see Httpservlet#doget (httpservletrequest request, HttpServletResponse R esponse) */protected void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {Connection conn = null; Statement stmt = null;//Sets the response content type Response.setcontenttype ("Text/html;charset=utf-8"); PrintWriter out = Response.getwriter (); String title = "Servlet Mysql"; String DocType = "<! DOCTYPE html>\n "; Out.println (DOCTYPE +" Java Servlet calls Database review