插入用户信息

问题:如果要在图书管理系统中创建用户,就需要使用JDBC连接数据库,在数据库保存用户信息。那么如何使用JDBC来完成这个过程呢?

解决方法
<%@ page language="java" import="java.util.*" import="java.sql.*"
	pageEncoding="GBK"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
	<head>
		<title>用户注册</title>
	</head>

	<body>
		<%
			//获取页面中的参数
			String username = request.getParameter("username");
			String birthdate = request.getParameter("birthdate");
			String sex = request.getParameter("sex");
			String password = request.getParameter("intro");
			String intro = request.getParameter("intro");
			String name = request.getParameter("name");
			String degree = request.getParameter("degree");
			String[] interest = request.getParameterValues("interest");
			StringBuffer s = new StringBuffer();
			for (int i = 0; i < interest.length; i++) {
				s.append(interest[i] + "");
			}
			String inte = s.toString();
			Connection conn = null;
			PreparedStatement ps = null;
			ResultSet rs = null;
			try {
				Class.forName("oracle.jdbc.driver.OracleDriver");
				String url = "jdbc:oracle:thin:@172.23.7.45:1521:netp";
				String user = "training";
				String passwd = "training";
				conn = DriverManager.getConnection(url, user, passwd);//连接数据库
				ps = conn
						.prepareStatement("insert into demo_users(userid,username,birthdate,sex,password,intro,realname,interest,degree) values(SEQ_DEMO_USERS.NEXTVAL,?,to_date(?,'yyyy-mm-dd'),?,?,?,?,?,?)");
				ps.setString(1, username);
				ps.setString(2, birthdate);
				ps.setString(3, sex);
				ps.setString(4, password);
				ps.setString(5, intro);
				ps.setString(6, name);
				ps.setString(7, inte);
				ps.setString(8, degree);
				ps.executeUpdate();
			} catch (Exception e) {
				System.out.println(e);
			} finally {
				//关闭连接
				if (rs != null) {
					try {
						rs.close();
					} catch (Exception e) {
						System.out.println(e);
					}
				}
				if (ps != null) {
					try {
						ps.close();
					} catch (Exception e) {
						System.out.println(e);
					}
				}
				if (conn != null) {
					try {
						conn.close();
					} catch (Exception e) {
						System.out.println(e);
					}
				}
			}
		%>
	</body>
</html>



从上面的程序,可以把使用JDBC连接数据库从而完成相应的操作归纳成以下几点:
1.载入JDBC驱动程序
2.定义连接URL
3.建立连接
4.常见语句对象
5.执行查询或更新
6.处理结果
7.关闭连接

你可能感兴趣的:(jdbc)