你的位置:首页 > Java教程

[Java教程]JSP之数据的更新

---------------------------------------数据的连接---------------------------------------

package com;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class ConnectionManager {  private static final String DRIVER_;  private static final String DATABASE_URL="jdbc:sqlserver://127.0.0.1:1433;databasename=news";  private static final String DATABASE_USER="sa";  private static final String DATABASE_PASSWORD="123456";  //连接数据库的方法
 public static Connection getConnection(){
  Connection dbConnection=null;
  try{
   Class.forName(DRIVER_CLASS);    dbConnection=DriverManager.getConnection(DATABASE_URL, DATABASE_USER, DATABASE_PASSWORD);   catch(Exception e){
   e.printStackTrace();   return dbConnection;  //关闭数据库连接的方法
 public static void  closeConnection(Connection dbConnection){
  try{
   if(dbConnection!=null&&(!dbConnection.isClosed())){
    dbConnection.close();   }
  catch(SQLException sqlEx){
   sqlEx.printStackTrace();    //关闭数据集
 public static void closeResultSet(ResultSet res){
  try{
   if(res!=null){
    res.close();
    res=null;   }
  catch(SQLException e){
   e.printStackTrace();  }  public static void closeStatement(PreparedStatement pStatement){
  try{
   if(pStatement!=null){
    pStatement.close();
    pStatement=null;   }
  catch(SQLException e){
   e.printStackTrace();  }
}

----------------------------------------数据的查询---------------------------------------

package com;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class NewFirstTitleDB5 {  public static void main(String[] args) {
  int id=0;
  Connection con=null;
  PreparedStatement pStatement=null;
  ResultSet resSet=null;
  try{    con=ConnectionManager.getConnection();
   //查询数据的SQL语句
   String strsql="select max(id) from FirstLeveTitle";    pStatement=con.prepareStatement(strsql);    resSet=pStatement.executeQuery();
   if(resSet.next()){
    id=resSet.getInt(1);   }
  catch(Exception e){
   e.printStackTrace();   finally{
   ConnectionManager.closeConnection(con);
   ConnectionManager.closeResultSet(resSet);
   ConnectionManager.closeStatement(pStatement);   System.out.println("新的新闻标题的ID为:"+(id+1));
  

我的问题网 www.shenzhidao.com 有关于网站的东西欢迎大家一起交流!