1. Download the MySQL JDBC driver
Address: https://dev.mysql.com/downloads/connector/
For convenience, choose your own compression package directly
Skip login, select Direct download
After the download is complete, unzip the Mysql-connector-java-5.1.42-bin.jar, copy
In the extracted file, locate the
Paste to Webcontent-web-inf-lib
Select the Lib folder in the Ecplise, and paste directly with Ctrl + V
2. Create a new. JSP page
Code:
<% @pageImport= "Java.text.SimpleDateFormat"%><% @pageImport= "Java.sql.Date"%><% @pageImport= "Java.sql.PreparedStatement"%><% @pageImport= "Java.sql.DriverManager"%><% @pageImport= "java.sql.Connection"%><%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding= "UTF-8"%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >Date Date=NewDate (Newjava.util.Date (). GetTime ()); Out.println ("Time:" +date);//Statement Name,timeString name = "Xiaoming";//Get current Time//Load DriverClass.forName ("Org.gjt.mm.mysql.Driver"); Out.println ("Load driver succeeded"); //database path saved to URL variableString url= "jdbc:mysql://127.0.0.1:3306/test1?user=root&password=123456"; //the statement to execute is saved to the SQL variable//Save Add Field statementString sql1= "ALTER TABLE tt2 ADD Birt Date"; //Save Add information StatementString sql = "INSERT into TT2 (Name,birt) VALUES (?,?)"; //Link DatabaseConnection conn =drivermanager.getconnection (URL);//the statement to prepare for execution//Add a field to the TT2 table BirtPreparedStatement PS1 =conn.preparestatement (SQL1); //input information name, BirtPreparedStatement PS2 =conn.preparestatement (SQL); //Find the 1th sign, give the value of namePs2.setstring (1, name); //find the 2nd sign, give the value of timePs2.setdate (2, date);//ExecutionPs1.execute ();p s2.execute ();//Close Link//disconnection of the JDBC interfacePs1.close (); Ps2.close (); //Database DisconnectConn.close (); Out.print ("Data has been added");%></body>3. Part of the code explanation 3.1 Understanding diagram:3.2 Path (URL) of the MySQL connection with JDBC3.3 Connection Object3.4 PreparedStatement Object3.5 Execute () methodPerform
3.6 Close () methodLearning summary------Connect MySQL with JDBC