接上次JDBC 使用Derby數據庫鏈接以後 此次嘗試使用MySql 鏈接=-=css
咱們得先下載Mysql的驅動包:mysql-connector-java-5.1.41-bin.jarhtml
下載以後 導入:java
完成這個以後咱們打開MySql Workbench 開啓本地數據庫 並建立 USERINFO 庫mysql
而後再到index.jsp中寫入:sql
<%@ page language="java" import="java.util.*,java.sql.*" pageEncoding="ISO-8859-1"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <% //聲明Connection對象 Connection con; //驅動程序名 String driver = "com.mysql.jdbc.Driver"; //URL指向要訪問的數據庫名mydata String url = "jdbc:mysql://localhost:3306/USERINFO"; //MySQL配置時的用戶名 String user = "root"; //MySQL配置時的密碼 String password = "699307"; //遍歷查詢結果集 Connection conn = null; try { //加載驅動程序 Class.forName(driver); //1.getConnection()方法,鏈接MySQL數據庫!! conn = DriverManager.getConnection(url,user,password); if(!conn.isClosed()) System.out.println("Succeeded connecting to the Database!"); //2.建立statement類對象,用來執行SQL語句!! Statement st = conn.createStatement(); //執行sql語句 String sql = "select * from USERINFO"; //增刪改查表中的內容,用executeUpdate方法 st.executeUpdate("insert into USERINFO(USERID, USERNAME) values (1, 'NOSTRING')"); st.executeUpdate("insert into USERINFO(USERID, USERNAME) values (2, 'BECHAR')"); st.executeUpdate("insert into USERINFO(USERID, USERNAME) values (3, 'ALEXVIEW')"); //讀取表的內容,用executeQuery方法 ResultSet rs = st.executeQuery("select * from USERINFO"); //循環輸出內容 while(rs.next()){ int userID = rs.getInt(1); String username = rs.getString(2); out.println("-------------------<br>"); out.println("uerid:"+ userID +"<br>"); out.println("username:"+ username +"<br>"); out.println("-------------------<br>"); } }catch(SQLException e){ out.print(e.getErrorCode() + "<br>"); out.print(e.getCause() + "<br>"); out.print(e.getMessage() + "<br>"); if(conn != null ) conn.close(); } %> </body> </html>
寫入以後平常訪問:數據庫