jsp是是在html中插入java代码段,那么jsp操作mysql其实和java是一样的。
首先要从mysql的官网下载MySQL Connector 当然我们选择Connector/J,下载以后将mysql-connector-java-5.1.20-bin.jar(5.1.20是版本号)放入tomcat安装目录下的lib目录内(我用的是tomcat7.0)当然如果你用的是5.x或者6.x的tomcat目录结构可能不一样,但是适当变通就行了,这个操作就相当于你在Eclipse中引入外部jar。
然后当然要在jsp中引入
<%@page import="com.mysql.jdbc.Driver,java.sql.*"%>
然后便可以想java中操作mysql那样写代码了。
<%
String username = "root";
String passwords = "123";
String driveName = "com.mysql.jdbc.Drive";
String url="jdbc:mysql://localhost/"+"test"+"?user="+username+"&password="+passwords;
String error="fail to connect to database";
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection connection=DriverManager.getConnection(url);
connection.close();
}catch(Exception e){
out.println(e.getMessage());
out.println(error);
}finally{}
%>
OK,完成。