JAVA手动连接数据库

// jsp
<%@ page language="java" import="java.util.*,java.sql.*"
	pageEncoding="GB18030"%>
<%@ page import="com.bjsxt.registration.service.*"%>
<%@ page import="com.bjsxt.registration.model.*"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";

	String username = request.getParameter("username");
	String password = request.getParameter("password");
	String password2 = request.getParameter("password2");
	System.out.println(username + "  " + password + "  " + password2);
	Class.forName("oracle.jdbc.driver.OracleDriver");
	Connection conn = DriverManager
			.getConnection("jdbc:oracle:thin:@localhost:1521:orcl",
					"system", "oracle");

	User u = new User();
	u.setUsername(username);
	u.setPassword(password);

	UserManager um = new UserManager();
	boolean exist = um.exists(u);
	if (exist) {
		response.sendRedirect("registerFail.jsp");
		return;
	}

	um.add(u);
	response.sendRedirect("registerSuccess.jsp");
%>
<%--
	String sqlQuery = "select count(*) from user1 where username = ?";
	PreparedStatement psQuery = conn.prepareStatement(sqlQuery);
	psQuery.setString(1, username);
	ResultSet rs = psQuery.executeQuery();
	rs.next();
	int count = rs.getInt(1);
	if (count > 0) {
		response.sendRedirect("registerFail.jsp");
		psQuery.close();
		conn.close();
		return;
	}

	String sql = "insert into user1 values (1, ?, ?)";
	PreparedStatement ps = conn.prepareStatement(sql);
	ps.setString(1, username);
	ps.setString(2, password);
	ps.executeUpdate();
	ps.close();
	conn.close();

	response.sendRedirect("registerSuccess.jsp");
--%>
 // service

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import com.bjsxt.registration.model.User;

public class UserManager {
	public boolean exists(User u) throws Exception {
		Class.forName("oracle.jdbc.driver.OracleDriver");
		Connection conn = DriverManager.getConnection(
				"jdbc:oracle:thin:@localhost:1521:orcl", "system", "oracle");

		String sqlQuery = "select count(*) from user1 where username = ?";
		PreparedStatement psQuery = conn.prepareStatement(sqlQuery);
		psQuery.setString(1, u.getUsername());
		ResultSet rs = psQuery.executeQuery();
		rs.next();
		int count = rs.getInt(1);
		psQuery.close();
		conn.close();

		if (count > 0) {
			return true;
		}
		return false;
	}

	public void add(User u) throws Exception {
		Class.forName("oracle.jdbc.driver.OracleDriver");
		Connection conn = DriverManager.getConnection(
				"jdbc:oracle:thin:@localhost:1521:orcl", "system", "oracle");

		String sql = "insert into user1 values (2, ?, ?)";
		PreparedStatement ps = conn.prepareStatement(sql);
		ps.setString(1, u.getUsername());
		ps.setString(2, u.getPassword());
		ps.executeUpdate();
		ps.close();
		conn.close();

	}
}

你可能感兴趣的:(java,oracle,sql,jsp,jdbc)