PackageDAO;Importjava.sql.Connection;ImportJava.sql.DriverManager;Importjava.sql.PreparedStatement;ImportJava.sql.ResultSet; Public classBasedao {PrivateString Driver = "Com.microsoft.sqlserver.jdbc.SQLServerDriver"; PrivateString url = "Jdbc:sqlserver://localhost:1433;databasename=easybuy"; PrivateString user = "sa"; PrivateString password = "sa"; /*** Get Database Connection Object * *@return */ PublicConnection getcconnection () {Connection conn=NULL; Try{class.forname (driver); Conn=drivermanager.getconnection (URL, user, password); } Catch(Exception e) {e.printstacktrace (); } returnConn; } /*** Close Database Connection object *@paramRS *@parampstmt *@paramConn*/ Public voidCloseAll (ResultSet rs,preparedstatement pstmt,connection conn) {Try { if(rs!=NULL) {rs.close (); } if(pstmt!=NULL) {pstmt.close (); } if(conn!=NULL) {conn.close (); } } Catch(Exception e) {e.printstacktrace (); } } /*** Adding and modifying methods *@paramSQL *@paramObjects *@return */ Public intexecuteupdate (String sql,object[] objects) {intNum=0; PreparedStatement pstmt=NULL; Connection Conn=getcconnection (); Try{pstmt=conn.preparestatement (SQL); for(inti = 0; i < objects.length; i++) {Pstmt.setobject (i+1, Objects[i]); } num=pstmt.executeupdate (); } Catch(Exception e) {e.printstacktrace (); }finally{CloseAll (NULL, PSTMT, conn); } returnnum; }}
The above is the specific steps of the Java connection database, shut down the database, it must be close to the query results RS, and then close pstmt, and then close the conn and open the contrary ~ ~ ~, here the three should be created connection, create query, and query results.
If you want to know that there is a connection before you create the query, the results are returned.
For Pstmt.setobject (i+1, objects[i]), this line of code, because the method refers to a mutable parameter (why to reference a mutable parameter, because the string is preceded by a database statement, type mismatch), the so-called mutable parameter is : For cases where the parameter number is indeterminate and the type is indeterminate, Java handles the mutable parameter as an array, but not an array, which is more powerful than an array and can be turned into no parameters or null. And this line of code is to assign the database statement to the parameter, because the parameter is starting from 1, so write i+1.
The specific operation of the linked database in Java and the meaning of the Pstmt.setobject (I+1, objects[i]) line of code