jsp连接数据库:
<%@ page language="java" import="java.util.*, java.sql.*" pageEncoding="GB18030"%>
<%
String username = request.getParameter("username");
String password = request.getParameter("password");
String password2 = request.getParameter("password2");
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/bishe", "root", "admin");
String sqlQuery = "select count(*) from user 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 user values (null, ?, ?)";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, username);
ps.setString(2, password);
ps.executeUpdate();
ps.close();
conn.close();
response.sendRedirect("registerSuccess.jsp");
%>
javaBean数据库连接:
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/spring", "root", "bjsxt");
String sql = "insert into user values (null, ?, ?)";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, u.getUsername());
ps.setString(2, u.getPassword());
ps.executeUpdate();
ps.close();
conn.close();
hibernate 数据操作
Configuration cfg = new Configuration().configure();
factory = cfg.buildSessionFactory().openSession();
Session session = HibernateUtil.getSession();
//开启事务
session.beginTransaction();
//保存数据
session.save(p);
//事务提交
session.getTransaction().commit();
//关闭session
HibernateUtil.closeSession(session);
本文出自 “sunnyting” 博客,请务必保留此出处http://sunnyting.blog.51cto.com/8814143/1559589