| 代碼如下 |
複製代碼 |
|
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)); |