当前位置: 技术问答>java相关
JSP中操作数据库是不是必须用BEAN?
来源: 互联网 发布时间:2015-02-08
本文导语: JSP中操作数据库是不是必须用BEAN?如果这样就不如ASP方便了。各JSP的服务器中是不是已内建了调用数据库的公用BEAN,可由开发者自由调用? | bean: import java.util.*; import java.sql.*; import java.io.*...
JSP中操作数据库是不是必须用BEAN?如果这样就不如ASP方便了。各JSP的服务器中是不是已内建了调用数据库的公用BEAN,可由开发者自由调用?
|
bean:
import java.util.*;
import java.sql.*;
import java.io.*;
import java.sql.*;
public class mysql {
Connection conn=null;
Statement statement=null;
PreparedStatement pstmt=null;
ResultSet rs=null;
public mysql(){
try{
Class.forName("org.gjt.mm.mysql.Driver");
}catch(ClassNotFoundException e)
{System.err.println("mysql():"+e.getMessage());}
String url="jdbc:mysql://localhost:3306/Sample?user=root;password=";
try{
conn=DriverManager.getConnection(url);
statement = conn.createStatement();
}catch(SQLException sqlEx)
{System.err.println(sqlEx.getMessage());}
}
public ResultSet executeQuery(String sql)
{
try{
rs = statement.executeQuery(sql);
}catch(SQLException ex)
{
System.err.println("executeQuery():"+ex.getMessage());
}
return rs;
}
public int executeUpdate(String sql)
{
int i=0;
try{
i = statement.executeUpdate(sql);
}catch(SQLException ex)
{
System.err.println("executeUpdate():"+ex.getMessage());
}
return i;
}
}
JSP:
import java.util.*;
import java.sql.*;
import java.io.*;
import java.sql.*;
public class mysql {
Connection conn=null;
Statement statement=null;
PreparedStatement pstmt=null;
ResultSet rs=null;
public mysql(){
try{
Class.forName("org.gjt.mm.mysql.Driver");
}catch(ClassNotFoundException e)
{System.err.println("mysql():"+e.getMessage());}
String url="jdbc:mysql://localhost:3306/Sample?user=root;password=";
try{
conn=DriverManager.getConnection(url);
statement = conn.createStatement();
}catch(SQLException sqlEx)
{System.err.println(sqlEx.getMessage());}
}
public ResultSet executeQuery(String sql)
{
try{
rs = statement.executeQuery(sql);
}catch(SQLException ex)
{
System.err.println("executeQuery():"+ex.getMessage());
}
return rs;
}
public int executeUpdate(String sql)
{
int i=0;
try{
i = statement.executeUpdate(sql);
}catch(SQLException ex)
{
System.err.println("executeUpdate():"+ex.getMessage());
}
return i;
}
}
JSP: