java 資料更新簡單一實例

來源:互聯網
上載者:User
 代碼如下 複製代碼

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_CLASS="com.microsoft.sqlserver.jdbc.SQLServerDriver";  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));

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.