1.Servlet与JDBC:
回去参考我java部分的jdbc部分的知识。(我把那里的例子搬到了这里)
在那里,我们提到最实用的单态模式的数据库连接池技术。这里需要注意的是,对于每个客户,tomcat都会用一个Servlet线程去应答。为了做到线程安全,在获取连接的方法上
getConnection(),应该加上Synchronized的关键字。如果对这部分知识感到困惑,
可以参考我的JDBC部分知识。另外既然这个项目是Web项目,对于导包我也要额外提一句。
对于web项目,我们必须拷贝mysql-connector-java-3.1
.jar到web\lib目录下。
例:4.1.1
package com;
import com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource;
import java.sql.*;
import javax.sql.*;
public class DatabaseConn {
static private MysqlConnectionPoolDataSource ds;
private DatabaseConn() {
ds = new MysqlConnectionPoolDataSource();
ds.setURL("jdbc:mysql://localhost:3306/test");
ds.setUser("root");
ds.setPassword("1234");
}
public synchronized static Connection getConnection() throws Exception {
if (ds == null) {
/*DatabaseConn的目的是让ds有值,和con无关*/
new DatabaseConn();
}
Connection con = null;
con = ds.getConnection();
return con;
}
}
测试servlet:
package com;
import java.io.IOException;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletHello1 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Connection con=null;
ResultSet rs=null;
Statement stmt=null;
try {
/* MysqlConnectionPoolDataSource ds is always in the memory once it is created becasue it is static..*/
con = DatabaseConn.getConnection();
stmt = con.createStatement();
rs = stmt.executeQuery("select * from login");
while (rs.next()) {
System.out.println(rs.getString("id"));
System.out.println(rs.getString("name"));
}
System.out.println("ok");
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
rs.close();
stmt.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
更多请见:http://www.mark-to-win.com/tutorial/jsp_2_ServletJDBC.html