修改Tomact下的conf-->context.xml文件,添加以下内容
<Resource name="jdbc/mysqlds" auth="Container" type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="10000"
username="root" password="123456" driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/blog"/> //数据库名称
servlet编写
DataSource ds = null;
try {
Context context = new InitialContext();
ds = (DataSource) context.lookup("java:/comp/env/jdbc/mysqlds"); //与上面的resource name一致
} catch (Exception e) {
System.out.println("获取数据源时出错");
}
Connection conn = ds.getConnection();
String sql = "insert into blog (title,content,category_id,createdtime) values (?,?,?,now())";
添加mysql驱动 mysql-connector-java-5.1.13-bin.jar
连接数据源出错,无法连接数据库解决
在项目的web.xml中添加
<resource-ref>
<description>DB Connection </description>
<res-ref-name>jdbc/mysqlds</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
在eclipse下部的Servers窗口中双击击Tomcat v7.0 Server at localhost,找到图中所示,将Server Locations选为第二项Use Tomcat…… 此选项为灰色无法选中,右击Servers-->new servers-->use Tomecat--->finnish
Server path:为tomcat所在目录
Deploy path:设为webapps
连接数据库成功