package student;
import java.sql.*;
public class stuBean1{
Connection con = null; //连接数据库
ResultSet rs = null;
Statement stmt = null;
private static stuBean1 me=new stuBean1();
public stuBean1 () {
}
public static stuBean1 newInstance(){
return me;
}
public Connection getConnDB(){
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance() ;
con=DriverManager.getConnection("jdbc:odbc:studb"); //连接数据源
} catch (Exception ex) {
ex.printStackTrace();
}
return con;
}
}
列界数据库的类.然后建个文件存放增删改查的超做。
下面是增加数据库的代码:
package student;
import java.sql.*;
public class stuBean1{
Connection con = null; //连接数据库
ResultSet rs = null;
Statement stmt = null;
private static stuBean1 me=new stuBean1();
public stuBean1 () {
}
public static stuBean1 newInstance(){
return me;
}
public Connection getConnDB(){
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance() ;
con=DriverManager.getConnection("jdbc:odbc:studb"); //连接数据源
} catch (Exception ex) {
ex.printStackTrace();
}
return con;
}
}
然后在在servlet文件里传值
package student;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
public class Servlet extends HttpServlet {
private static final String CONTENT_TYPE = "text/html; charset=GBK";
//Initialize global variables
public void init() throws ServletException {
}
//Process the HTTP Get request
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType(CONTENT_TYPE);
PrintWriter out = response.getWriter(); //从文本框中获取值
response.setCharacterEncoding("GB2312");
String loginName=request.getParameter("loginName");
String password=request.getParameter("password");
String truename=request.getParameter("truename");
String semester=request.getParameter("term");
semester = semester.trim();
System.out.println(semester);
studentBean1 bean=new studentBean1();
bean.setLoginName(loginName);
bean.setPassword(password);
bean.setTrurname(truename);
bean.setSemester(semester);
insert bean1=new insert();
int result=0;
result=bean1.getinsert(bean); //调用方法做增加数据
if (result>0)
{
request.getRequestDispatcher("rightmain.jsp").forward(request,response);
}
else
{
request.getRequestDispatcher("error.jsp").forward(request,response);
}
out.close();
}
//Process the HTTP Post request
public void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
doGet(request, response);
}
//Clean up resources
public void destroy() {
}
}