| 導購 | 订阅 | 在线投稿
分享
 
 
 

Jsp,JavaBean,Mysql的連接方法

2007-02-01 20:10:33  編輯來源:互聯網  简体版  手機版  評論  字體: ||
 
  Jsp,JavaBean,Mysql的連接方法
  利用JSP實現Web與數據庫的連接:
  (1).完成環境設置,導入java.sql包,命令如下:
   import java.sql.*
  (2).載入驅動器
  (3).連接到數據庫
  (4).語句接口
  (5).獲得結果集
  1. 測試環境:
  windows 2003
  j2sdk1.4.2_06
  Tomcat 5.0
  mysql-4.0.23-win
  mm.mysql-2.0.4-bin.jar
  2. 建立數據庫及表
  在Mysql中建個publish數據庫,並建個book表。在book中添加id,title,price
  3. JavaBean的代碼: dbconn.java
  package Border;
  import java.sql.*; //完成環境設置,導入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+"?useUnicode=true&characterEncoding=GBK&user="+user+"&password="+pass;
  public Connection getConn(){ //get database connection
   try{
   Class.forName(drivername).newInstance(); //載入驅動器
   conn = DriverManager.getConnection(URL); //連接到數據庫
   }
   catch(Exception e){
   e.printStackTrace();
   }
   return conn ;
  }
  public ResultSet executeSQL(String str) {
   try{
   Statement stmt = conn.createStatement(); //語句接口
   rs = stmt.executeQuery(str); //獲得結果集
   }
   catch(Exception e){
   e.printStackTrace();
   }
   return rs;
  }
  }
  編譯javac dbconn.java,將編譯後的文件dbconn.class放到目錄 "你的項目"\WEB-INF\classes\Border\下
  4. 調用Java Bean的JSP文件test.jsp
  <%@ page contentType="text/html;charset=GBK" import="java.sql.*"%>
  <jsp:useBean id="Border" scope="page" class="Border.dbconn" />
  <%
  ResultSet rs = null;
  Connection conn = null;
  conn = Border.getConn() ;
  rs = Border.executeSQL("select * from book");
  %>
  <html>
   <body>
   <br>
  <h2 align="center" > My first Jsp JavaBean Mysql </h2>
  <br>
   <table border="1" align="center">
   <tr>
   <th>
   id
   </th>
   <th>
   title
   </th>
   <th>
   price
   </th>
   </tr>
  
   <%
   while(rs.next()) {
   %>
   <tr>
   <th>
   <%=rs.getString("id")%>
   </th>
   <th>
   <%=rs.getString("title")%>
   </th>
   <th>
   <%=rs.getString("price")%>
   </th>
   </tr>
   <%}%>
   <%
   rs.close();
   conn.close();
   %>
   </table>
  <form name="form1" method="post" action="update.jsp">
   <table width="210" border="1" align="center" cellpadding="0" cellspacing="0">
   <tr>
   <td width="77">title:</td>
   <td width="127"><label>
   <input name="Title" type="text" id="Title">
   </label></td>
   </tr>
   <tr>
   <td>price:</td>
   <td><label>
   <input name="Price" type="text" id="Price">
   </label></td>
   </tr>
   <tr>
   <td><div align="right">
   <label>
   <input type="submit" name="Submit" value="提交">
   </label>
   </div></td>
   <td><label>
   <input type="reset" name="Submit2" value="重置">
   </label></td>
   </tr>
   </table>
   </form>
   </body>
  </html>
  5. update.jsp 寫入數據庫
  <%@ page contentType="text/html;charset=GBK" import="java.sql.*"%>
  <% request.setCharacterEncoding("GBK"); %>
  <jsp:useBean id="Border" scope="page" class="Border.text" />
  <%
  Connection conn = null;
  conn = Border.getConn() ;
   String tit=request.getParameter("Title");
   String prc=request.getParameter("Price");
  
   Statement stmt = conn.createStatement();
   stmt.executeUpdate("INSERT INTO book (title,price) VALUES ('"+tit+"','"+prc+"')");
  %>
  <jsp:forward page="text.jsp" />
  6. 提供幾個函數:
  (1). getConnection
  public static Connection getConnection(String url,
   String user,
   String password)
   throws SQLException
  Attempts to establish a connection to the given database URL. The DriverManager attempts to select an appropriate driver from the set of registered JDBC drivers.
  Parameters:
  url - a database url of the form jdbc:subprotocol:subname
  user - the database user on whose behalf the connection is being made
  password - the user's password
  Returns:
  a connection to the URL
  Throws:
  SQLException - if a database access error occurs
  (2). createStatement
  public Statement createStatement()
   throws SQLException
  Creates a Statement object for sending SQL statements to the database. SQL statements without parameters are normally executed using Statement objects. If the same SQL statement is executed many times, it may be more efficient to use a PreparedStatement object.
  Result sets created using the returned Statement object will by default be type TYPE_FORWARD_ONLY and have a concurrency level of CONCUR_READ_ONLY.
  Returns:
  a new default Statement object
  Throws:
  SQLException - if a database access error occurs
  (3). executeQuery
  public ResultSet executeQuery(String sql)
   throws SQLException
  Executes the given SQL statement, which returns a single ResultSet object.
  Parameters:
  sql - an SQL statement to be sent to the database, typically a static SQL SELECT statement
  Returns:
  a ResultSet object that contains the data produced by the given query; never null
  Throws:
  SQLException - if a database access error occurs or the given SQL statement produces anything other than a single ResultSet object
  (4). getString
  public String getString(String columnName)
   throws SQLException
  Retrieves the value of the designated column in the current row of this ResultSet object as a String in the Java programming language.
  Parameters:
  columnName - the SQL name of the column
  Returns:
  the column value; if the value is SQL NULL, the value returned is null
  Throws:
  SQLException - if a database access error occurs
  (5). next
  public boolean next()
   throws SQLException
  Moves the cursor down one row from its current position. A ResultSet cursor is initially positioned before the first row; the first call to the method next makes the first row the current row; the second call makes the second row the current row, and so on.
  If an input stream is open for the current row, a call to the method next will implicitly close it. A ResultSet object's warning chain is cleared when a new row is read.
  Returns:
  true if the new current row is valid; false if there are no more rows
  Throws:
  SQLException - if a database access error occurs
  7. ok! Now game is over~~
  8. 若您覺得滿意,想轉載或收藏這篇文章,我非常感謝,但請您注明作者: border ( border@hacker.cn )
   http://blog.csdn.net/border1985
  最後歡迎大家訪問 --中國安全信息網-- http://www.hacker.cn/
 
Jsp,JavaBean,Mysql的連接方法 利用JSP實現Web與數據庫的連接: (1).完成環境設置,導入java.sql包,命令如下: import java.sql.* (2).載入驅動器 (3).連接到數據庫 (4).語句接口 (5).獲得結果集 1. 測試環境: windows 2003 j2sdk1.4.2_06 Tomcat 5.0 mysql-4.0.23-win mm.mysql-2.0.4-bin.jar 2. 建立數據庫及表 在Mysql中建個publish數據庫,並建個book表。在book中添加id,title,price 3. JavaBean的代碼: dbconn.java package Border; import java.sql.*; //完成環境設置,導入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+"?useUnicode=true&characterEncoding=GBK&user="+user+"&password="+pass; public Connection getConn(){ //get database connection try{ Class.forName(drivername).newInstance(); //載入驅動器 conn = DriverManager.getConnection(URL); //連接到數據庫 } catch(Exception e){ e.printStackTrace(); } return conn ; } public ResultSet executeSQL(String str) { try{ Statement stmt = conn.createStatement(); //語句接口 rs = stmt.executeQuery(str); //獲得結果集 } catch(Exception e){ e.printStackTrace(); } return rs; } } 編譯javac dbconn.java,將編譯後的文件dbconn.class放到目錄 "你的項目"\WEB-INF\classes\Border\下 4. 調用Java Bean的JSP文件test.jsp <%@ page contentType="text/html;charset=GBK" import="java.sql.*"%> <jsp:useBean id="Border" scope="page" class="Border.dbconn" /> <% ResultSet rs = null; Connection conn = null; conn = Border.getConn() ; rs = Border.executeSQL("select * from book"); %> <html> <body> <br> <h2 align="center" > My first Jsp JavaBean Mysql </h2> <br> <table border="1" align="center"> <tr> <th> id </th> <th> title </th> <th> price </th> </tr> <% while(rs.next()) { %> <tr> <th> <%=rs.getString("id")%> </th> <th> <%=rs.getString("title")%> </th> <th> <%=rs.getString("price")%> </th> </tr> <%}%> <% rs.close(); conn.close(); %> </table> <form name="form1" method="post" action="update.jsp"> <table width="210" border="1" align="center" cellpadding="0" cellspacing="0"> <tr> <td width="77">title:</td> <td width="127"><label> <input name="Title" type="text" id="Title"> </label></td> </tr> <tr> <td>price:</td> <td><label> <input name="Price" type="text" id="Price"> </label></td> </tr> <tr> <td><div align="right"> <label> <input type="submit" name="Submit" value="提交"> </label> </div></td> <td><label> <input type="reset" name="Submit2" value="重置"> </label></td> </tr> </table> </form> </body> </html> 5. update.jsp 寫入數據庫 <%@ page contentType="text/html;charset=GBK" import="java.sql.*"%> <% request.setCharacterEncoding("GBK"); %> <jsp:useBean id="Border" scope="page" class="Border.text" /> <% Connection conn = null; conn = Border.getConn() ; String tit=request.getParameter("Title"); String prc=request.getParameter("Price"); Statement stmt = conn.createStatement(); stmt.executeUpdate("INSERT INTO book (title,price) VALUES ('"+tit+"','"+prc+"')"); %> <jsp:forward page="text.jsp" /> 6. 提供幾個函數: (1). getConnection public static Connection getConnection(String url, String user, String password) throws SQLException Attempts to establish a connection to the given database URL. The DriverManager attempts to select an appropriate driver from the set of registered JDBC drivers. Parameters: url - a database url of the form jdbc:subprotocol:subname user - the database user on whose behalf the connection is being made password - the user's password Returns: a connection to the URL Throws: SQLException - if a database access error occurs (2). createStatement public Statement createStatement() throws SQLException Creates a Statement object for sending SQL statements to the database. SQL statements without parameters are normally executed using Statement objects. If the same SQL statement is executed many times, it may be more efficient to use a PreparedStatement object. Result sets created using the returned Statement object will by default be type TYPE_FORWARD_ONLY and have a concurrency level of CONCUR_READ_ONLY. Returns: a new default Statement object Throws: SQLException - if a database access error occurs (3). executeQuery public ResultSet executeQuery(String sql) throws SQLException Executes the given SQL statement, which returns a single ResultSet object. Parameters: sql - an SQL statement to be sent to the database, typically a static SQL SELECT statement Returns: a ResultSet object that contains the data produced by the given query; never null Throws: SQLException - if a database access error occurs or the given SQL statement produces anything other than a single ResultSet object (4). getString public String getString(String columnName) throws SQLException Retrieves the value of the designated column in the current row of this ResultSet object as a String in the Java programming language. Parameters: columnName - the SQL name of the column Returns: the column value; if the value is SQL NULL, the value returned is null Throws: SQLException - if a database access error occurs (5). next public boolean next() throws SQLException Moves the cursor down one row from its current position. A ResultSet cursor is initially positioned before the first row; the first call to the method next makes the first row the current row; the second call makes the second row the current row, and so on. If an input stream is open for the current row, a call to the method next will implicitly close it. A ResultSet object's warning chain is cleared when a new row is read. Returns: true if the new current row is valid; false if there are no more rows Throws: SQLException - if a database access error occurs 7. ok! Now game is over~~ 8. 若您覺得滿意,想轉載或收藏這篇文章,我非常感謝,但請您注明作者: border ( [url=mailto:border@hacker.cn]border@hacker.cn[/url] ) [url=http://blog.csdn.net/border1985]http://blog.csdn.net/border1985[/url] 最後歡迎大家訪問 --中國安全信息網-- [url=http://www.hacker.cn/]http://www.hacker.cn/[/url]
󰈣󰈤
 
 
 
>>返回首頁<<
 
 
 
 
 熱帖排行
 
王朝網路微信公眾號
微信掃碼關註本站公眾號 wangchaonetcn
 
  免責聲明:本文僅代表作者個人觀點,與王朝網絡無關。王朝網絡登載此文出於傳遞更多信息之目的,並不意味著贊同其觀點或證實其描述,其原創性以及文中陳述文字和內容未經本站證實,對本文以及其中全部或者部分內容、文字的真實性、完整性、及時性本站不作任何保證或承諾,請讀者僅作參考,並請自行核實相關內容。
 
© 2005- 王朝網路 版權所有