Objective:
Learn to install databases (MySQL) and load JDBC drivers
Master how to connect to MySQL in JSP and perform operations such as creating database tables, adding, updating, and deleting records
(1) Download and install MySQL
For more information, see Baidu.
(2) Download and install MySQL
Mysql, find the download link to download mysql-connector-java-xxxx.zip
Install MySQL by copying the downloaded mysql-conntector-java-xxx.zip extracted mysql-conntector-java-XXX.jar to the lib Directory of the Web project's WEB-INF directory.
(3) load the JDBC driver
Before connecting JDBC to a database, you must load the appropriate driver. Method: use the forName method of Class to load the driver.
Example:
<% @ Page language = "java" contentType = "text/html; charset = gb2312" %>
Load JDBC driver
<%
Try {
Class. forName ("com. mysql. jdbc. Driver"); // load the JDBC Driver
} Catch (ClassNotFoundException e ){
Out. println ("failed to load the driver ");
}
%>
<%
String url = "URL of the database instance ";
String user = "root"; // user name
String passwd = "XXX"; // connection password
Connection conn = null;
Try {
Class. forName ("com. mysql. jdbc. Driver"); // load the JDBC Driver
Conn = DriverManager. getConnection (url, user, passwd );
} Catch (ClassNotFoundException e ){
Out. println ("driver class not found ");
} Catch (SQLException e ){
Out. println ("MySQL connection failed ");
}
Try {
// Create a Statement
Statement stmt = conn. createStatement ();
// Add a record
String SQL = "insert into user (id, name, password) values (20140414, 'Bruce ', '123 ')";
// Execute the SQL statement
Stmt.exe cuteUpdate (SQL );
} Catch (SQLException e ){
Out. println ("failed to add user information ");
}
// Close the database
Try {
If (stmt! = Null ){
Stmt. close ();
Stmt = null;
}
If (conn! = Null ){
Conn. close ();
Conn = null;
}
} Catch (Exception e ){
Out. println ("database shutdown exception ");
}
%>
For other operations, you only need to change the SQL statement.
Of course, there are also ResultSet and PreparedStatement objects. if you don't want to write them, baidu or Google.
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.