现在的位置: 首页 > 综合 > 正文

JAVA WEB_JSP的初步(14)JDBC

2018年01月09日 ⁄ 综合 ⁄ 共 1031字 ⁄ 字号 评论关闭
<%@ page language="java" import="java.sql.*" pageEncoding="GBK"%>
<html>
	<head>
		<title>JDBC</title>
	</head>
	<body>
		<%!
			ResultSet rs = null;
			PreparedStatement pstmt = null;
			Connection conn = null;
		%>
		<%
			try {
				Class.forName("com.mysql.jdbc.Driver");
				conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydata","root", "root");
				pstmt = conn.prepareStatement("insert into student(Name,Age,Tel,Address) values (?, ?, ?,?)");
				pstmt.setString(1, "wang");
				pstmt.setInt(2, 21);
				pstmt.setString(3, "123456789");
				pstmt.setString(4, "shanghai");
				pstmt.executeUpdate();
				Statement st = conn.createStatement();
				rs = st.executeQuery("select * from student");
				while(rs.next()) {
					out.println(" " + rs.getString("Name"));
					out.println(" " + rs.getInt("Age"));
					out.println(" " + rs.getString("Tel"));
					out.println(" " + rs.getString("Address"));
					out.println("<br>");
				}
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			} catch (SQLException e) {
				e.printStackTrace();
			} finally {
				try {
					if (rs != null) {
				rs.close();
					}
					if (pstmt != null) {
				pstmt.close();
					}
					if (conn != null) {
				conn.close();
					}
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		%>
	</body>
</html>

抱歉!评论已关闭.