JSP, JavaBean, Mysql connection method
Use JSP to implement the connection of Web and databases:
(1). Complete environment settings, import java.sql package, command as follows: import java.sql. *
(2). Load driver
(3). Connect to the database
(4). Statement interface
(5). Get result set
1. Test environment:
WINDOWS 2003
J2SDK1.4.2_06
Tomcat 5.0
Mysql-4.0.23-win
mm.mysql-2.0.4-bin.jar
2. Establish a database and table
Built a publish database in MySQL and build a BOOK table. Add ID, Title, Price to Book
3. JavaBean code: dbconn.java
package Border; import java.sql *;. // complete environment setting, introducing the package java.sql public class dbconn {public dbconn () {} // declare variable private Connection conn = null; private ResultSet rs = null; private String server = "127.0.0.1"; // can't use localhost, you must use ip or cname private string port = "3306"; // change to your port private string db = "publish"; // change to your db name private String user = "root"; // change to your username private String pass = "root"; // change to your password private String drivername = "org.gjt.mm.mysql.Driver"; // mysql driver private String URL = "JDBC: MySQL: //" Server ":" Port "/" DB "User " & Password = " Pass;
Public connection getConn () {// get database connections Try {class.Forname (DRIVERNAME) .newinstance (); // Load Drive Conn = DriverManager.getConnection (URL); // Connect to Database} Catch (Exception E) { E.PrintStackTrace ();} Return CONN;
Public ResultSet ExecuteSQL (String Str) {Try {Stmt = Conn.createStatement (); // Statement Interface RS = Stmt.executeQuery (STR); // Get Result Set} Catch (Exception E) {E.PrintStackTrace (); } RETURN RS;}}
Compile Javac dbconn.java, put the compiled file dbconn.class to the directory "Your Project" / Web-INF / CLASSES / BORDER / 9. Test. JSP file Test.jsp of Java Bean
<% @ Page ContentType = "text / html; charset = GBK" import = "java.sql. *"%>