网页中用jsp技术加载数据库的方式
通常executeUpdate用来进行数据库的删除,修改和添加
通常executeQuery用来进行查询数据库
DriverManager.getConnection(sConnStr,username,password); // 连接数据库
Connection conn=null;
Statement stmt=null;
ResultSet rs=null;
String sDBDriver = "com.mysql.jdbc.Driver";
String sConnStr = "jdbc:mysql://localhost:3306/test";
String username = "mysql用户名";
String password = "mysql密码";
try{
Class.forName(sDBDriver); // 获取数据库类
}
catch(ClassNotFoundException ex){
System.err.println(ex.getMessage());
}
try{
conn=DriverManager.getConnection(sConnStr,username,password); // 连接数据库
stmt=conn.createStatement(); // Statement为一条Sql语句生成执行计划
String sql="select * from user"; //通常executeUpdate用来进行数据库的删除,修改和添加
rs=stmt.executeQuery(sql); // 通常executeQuery用来进行查询数据库
if(rs!=null){ // rs!=null代表有数据
while(rs.next()){ // 数据处理
int id=rs.getInt("id"); // 获取整数类型
String username=rs.getString ("username"); // 获取字符类型
String password=rs.getString("password");
}
}
}
catch(SQLException el){
out.println(el);
}
finally{
conn.close(); // 断开数据库的连接
}
但以为网页上要经常用到数据库存储和加载,每次都写一样的代码,重复的写导致代码重复量大,不易于修改,于是将数据库的加载方式写成一个套路,因为加载数据库的方式都是一样的,于是弄成一个java类,要使用的时候直接调用java的class就可以了 ,于是有了下面的代码。
public class DBGet{
static String sDBDriver = "com.mysql.jdbc.Driver";
static String sConnStr = "jdbc:mysql://localhost:3306/test?characterEncoding=utf8";
static String username = "mysql用户名";
static String password = "mysql密码";
//返回Connection对象
public static Connection getConnection(){
Connection conn=null;
try{
Class.forName(sDBDriver);
conn=DriverManager.getConnection(sConnStr,username,password);
}
catch(ClassNotFoundException ex){
System.out.println(ex.getMessage());
}
catch(SQLException ex){
System.out.println(ex.getMessage()+"dbget");
}
return conn;
}
//关闭Connection对象
public static void closeConnection(Connection conn){
try{
if(conn!=null){
conn.close();
}
}
catch(SQLException ex){
System.out.println(ex.getMessage());
}
}
}
有的时候需要加载大量的数据,可以用ArrayList<class>的方式返回数据。
public ArrayList<News> getAllNews(){
News news=null;
ArrayList<News> newsList=new ArrayList<News>();
Connection conn=null;
ResultSet rs=null;
Statement stmt=null;
try{
conn=DBGet.getConnection();
stmt=conn.createStatement();
String sql="select * from news";
rs=stmt.executeQuery(sql);
while(rs.next()){
news=new News();
news.setId(rs.getInt("id"));
news.setTitle(rs.getString("title"));
news.setContent(rs.getString("content"));
news.setAuthor(rs.getString("author"));
news.setPubtime(rs.getString("pubtime"));
news.setKeyword(rs.getString("keyword"));
news.setAcnumber(rs.getInt("acnumber"));
newsList.add(news);
}
}catch(SQLException ex){
System.out.println(ex+"dao");
}finally{
DBGet.closeConnection(conn);
}
return newsList;
}