当前位置:Gxlcms > 数据库问题 > 一个简单的JSP 连接MySQL使用实例

一个简单的JSP 连接MySQL使用实例

时间:2021-07-01 10:21:17 帮助过:26人阅读

 
  1. <%@ page contentType="text/html; charset=gb2312" %>   
  2. <%@ page language="java" %>   
  3. <%@ page import="com.mysql.jdbc.Driver" %>   
  4. <%@ page import="java.sql.*" %>   
  5. <%   
  6. //加载驱动程序   
  7. String driverName="com.mysql.jdbc.Driver";   
  8. //数据库信息  
  9. String userName="root";   
  10. //密码   
  11. String userPasswd="123";   
  12. //数据库名   
  13. String dbName="Student";   
  14. //表名   
  15. String tableName="stu_info";   
  16. //将数据库信息字符串连接成为一个完整的url(也可以直接写成url,分开写是明了可维护性强)   
  17.   
  18. String url="jdbc:mysql://localhost/"+dbName+"?user="+userName+"&password="+userPasswd;   
  19. Class.forName("com.mysql.jdbc.Driver").newInstance();   
  20. Connection conn=DriverManager.getConnection(url);   
  21. Statement stmt = conn.createStatement();   
  22. String sql="SELECT * FROM "+tableName;   
  23. ResultSet rs = stmt.executeQuery(sql);   
  24. out.print("id");   
  25. out.print("|");   
  26. out.print("name");   
  27. out.print("|");   
  28. out.print("phone");   
  29. out.print("<br>");   
  30. while(rs.next()) {   
  31. out.print(rs.getString(1)+" ");   
  32. out.print("|");   
  33. out.print(rs.getString(2)+" ");   
  34. out.print("|");   
  35. out.print(rs.getString(3));   
  36. out.print("<br>");   
  37. }   
  38. out.print("<br>");   
  39. out.print("ok, Database Query Successd!");   
  40. rs.close();   
  41. stmt.close();   
  42. conn.close();   
  43. %>  
  44.    
 

 


在浏览器端打开我们的页面 类似于:http://localhost:8080/Test/test.jsp就可以看到查询的数据了。

from: http://blog.csdn.net/kirinlau/article/details/53182789

一个简单的JSP 连接MySQL使用实例

标签:配置   out   statement   path   需要   cut   msi   ble   rac   

人气教程排行