Previously, I had the experience of successfully connecting to MySQL through JDBC when writing an application.
Can I use the same code to connect to MySQL on a web page written in JSP?
The result is no. When I copy the same code to a file, an error occurs.
So Baidu fawei found a related article. After research, we only need to make some changes.
Change the original driver manager:
Class. forname ("org. gjt. Mm. MySQL. Driver ");
The following code can be used as a reference:
<HTML>
<Head> <title> helloworld. jsp </title> <Body>
<% @ Page Language = "Java" Import = "Java. SQL. *" %>
<%
Try {
Class. forname ("org. gjt. Mm. MySQL. Driver ");
Out. println ("Success loading MySQL driver! ");
}
Catch (exception E)
{
Out. Print ("error loading MySQL driver! ");
E. printstacktrace ();
}
Try {
Connection connect = drivermanager. getconnection ("JDBC: mysql: // localhost/jdbctest", "userid", "password ");
Out. Print ("Success connect MySQL server! ");
Statement stmt = connect. createstatement ();
Resultset rs1_stmt.exe cutequery ("select * from employees ");
While (Rs. Next ())
{
Out. println (Rs. getint (1 ));
Out. println (Rs. getstring (2 ));
Out. println (Rs. getint (3 ));
Out. println (Rs. getint (4 ));
}
}
Catch (exception E)
{
Out. Print ("Get data error! ");
E. printstacktrace ();
}
%>
</Body> NOTE: For the download of the MySQL JDBC driver, refer to my previous article.
After downloading the JAR file, copy it to the common/lib directory under the tomcat installation directory (I use the Tomcat server, but I have not studied other types of servers ).