Import Java. io. *; import Java. SQL. connection; import Java. SQL. drivermanager; import Java. SQL. sqlexception; import Java. SQL. statement; import javax. servlet. *; import javax. servlet. HTTP. *; public class creatdbservlet extends httpservlet {private string URL, user, password; @ overridepublic void Init () throws servletexception {// todo auto-generated method stubstring driverclass = This. getinitparameter ("drivercia SS "); url = This. getinitparameter ("url"); User = This. getinitparameter ("user"); Password = This. getinitparameter ("password"); try {class. forname (driverclass);} catch (CE) {Throw new servletexception (driverclass + "Database loading failed");} protected void doget (httpservletrequest req, httpservletresponse resp) throws servletexception, ioexception {// todo auto-generated method stub // super. doget (req, Resp); connection conn = NULL; statement stmt = NULL; try restarting cuteupdate ("drop database if exists Bookstore" without using stmt.exe cuteupdate ("create database Bookstore" without using stmt.exe cuteupdate ("use Bookstore" without using stmt.exe cuteupdate ("create table bookinfo (ID int not null primary key, title varchar (50) not null, author varchar (50) not null, B Ookconcern varchar (100) not null, publish_date date not null, price float (200) not null, amount smallint, remark varchar () engine = InnoDB "); stmt. addbatch ("insert into bookinfo values (1, 'java web developer', 'author ','..... ', '2014-4-20', 2006, 35, null) "initialize stmt.exe cutebatch (); resp. setcontenttype ("text/html; charset = GBK"); printwriter out = resp. getwriter (); out. println ("success, database created successfully"); out. close ();} catch (sqlexcep Tion SE) {Throw new servletexception (SE) ;}finally {If (stmt! = NULL) {try {stmt. Close () ;}catch (sqlexception SE) {se. printstacktrace () ;}stmt = NULL ;}if (Conn! = NULL) {try {Conn. close ();} catch (sqlexception SE) {se. printstacktrace () ;}conn = NULL ;}}@ overrideprotected void dopost (httpservletrequest req, httpservletresponse resp) throws servletexception, ioexception {// todo auto-generated method stub/super. dopost (req, resp); doget (req, resp );}}
Copy the path of the jdbc driver mysql-connector-java-5.1.18-bin.jar of mysql to the classpath of the Environment Variable added by the mysql-connector-java-5.1.18-bin.jar and copy it to the common \ lib in the tomcat directory.
Configure parameters in web. xml
</Servlet> <servlet-Name> creatdbservlet </servlet-Name> <servlet-class> creatdbservlet </servlet-class> <init-param> <param-name> driverclass </param-Name> <param-value> COM. mySQL. JDBC. driver </param-value> </init-param> <param-Name> User </param-Name> <param-value> root </param- value> </init-param> <param-Name> password </param-Name> <param-value> MySQL Root Password </param-value> </init-param> <param-Name> URL </param-Name> <param-value> JDBC: mySQL: // localhost: 3306 </param-value> </init-param> </servlet>