標籤:jsp串連資料庫
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
jsp串連資料庫