| The code is as follows: |
Copy code |
|
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"; // method for connecting to the database
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; // method for closing the database connection
Public static void closeConnection (Connection dbConnection ){
Try {
If (dbConnection! = Null &&(! DbConnection. isClosed ())){
DbConnection. close ();}
Catch (SQLException sqlEx ){
SqlEx. printStackTrace (); // Close the dataset
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 ();}
} |
---------------------------------------- Data query ---------------------------------------
| The code is as follows: |
Copy code |
|
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 statement for data query
String strsql = "select max (id) from FirstLeveTitle"; pStatement = con. prepareStatement (strsql); resset1_pstatement.exe cuteQuery ();
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 ("The ID of the new News title is:" + (id + 1 )); |