1. 程式人生 > >驗證myeclipse通過jsp連線mysql資料庫是否成功

驗證myeclipse通過jsp連線mysql資料庫是否成功

首先,我們需要建立一個數據庫和表

比如我們create database a

然後我們可以建立表

這樣我們就建立了一個數據庫和一張表,然後我們需要實現子jsp中判斷是否連線進入資料庫

程式碼:

<%@ page language="java" import="java.util.*,java.sql.*" pageEncoding="UTF-8"%>
<%
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>利用PreparedStatement物件新增一條記錄頁面</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>
  <%String driverName="com.mysql.jdbc.Driver";
    String userName="root";
    String userPwd="lytwy123456";
    String dbName="a";
    String url1="jdbc:mysql://localhost:3306/"+dbName;
    String url2="?user="+userName+"&password="+userPwd;
    String url3="&useUnicode=true&characterEncoding=UTF-8";
    String ur1=url1+url2+url3;
    Class.forName(driverName);
    Connection conn=DriverManager.getConnection(ur1);
    String sql="Insert into info(id,name,sex,age,weight,hight)values(?,?,?,?,?,?)";
    PreparedStatement pstmt=conn.prepareStatement(sql);
    pstmt.setInt(1,36);
    pstmt.setString(2,"李四");
    pstmt.setString(3,"男");
    pstmt.setInt(4,45);
    pstmt.setFloat(5,53);
    pstmt.setFloat(6,177);
    int n=pstmt.executeUpdate();
    if(n==1){%> 資料庫插入操作成功!<br><%}
    else{%> 資料庫插入操作失敗!<br><%}
    if(pstmt!=null){pstmt.close();}
    if(conn!=null){conn.close();} %>
  </body>

</html>

你使用的時候需要結合自己的資料庫密碼還有操作的資料庫名,表名等,通過插入一個數據是否插入成功即可判斷是否連線成功。

頁面顯示插入成功,我們在看資料庫內容是否改變

很明顯已經連線成功mysql了。