1 PackageDatabase;2 ImportJava.sql.*;3 Public classDbutil {4 //Here you can set the database name5 Private Final StaticString URL = "Jdbc:sqlserver://127.0.0.1:1433;databasename=mythree"; 6 Private Static FinalString user= "SA"; 7 Private Static FinalString password= "123"; 8 Private StaticConnection conn=NULL; 9 //Static code block (load driver, connect database into static block)Ten Static{ One Try { A - //1. Loading drivers -Class.forName ("Com.microsoft.sqlserver.jdbc.SQLServerDriver"); the //2. Get a connection to the database -conn=(Connection) drivermanager.getconnection (Url,user,password); - } - Catch(ClassNotFoundException e) { + e.printstacktrace (); -}Catch(SQLException e) { + e.printstacktrace (); A } at } - //provides a way to get a database connection - Public StaticConnection getconnection () { - returnConn; - } - //Enquiry in Public voidSelect (Statement stmt)throwsSQLException { -ResultSet rs = stmt.executequery ("select * from Li Yunchen. Course Selection"); to while(Rs.next ()) { + //If there is data in the object, it will be printed in a loop. -System.out.println ("School Number =" +rs.getint ("School Number") + "Course number =" +rs.getint ("course number") + "test result =" +rs.getint ("Exam results"))); the * //System.out.println (Rs.getint ("teacher number") + "," +rs.getstring ("name") + "," +rs.getint ("professional")); $ } Panax Notoginseng } - //Insert the Public voidInsert (Statement stmt)throwsSQLException { + //success-returns false A BooleanExecute = Stmt.execute ("INSERT into Li Yunchen. Selected values (1,2,100)"); the System.out.println (execute); + } - //Update $ Public voidUpdate (Statement stmt)throwsSQLException { $ //return ordinal - intExecuteupdate = stmt.executeupdate ("Update Li Yunchen." Select the set test result =90 where study number = 1 "); - System.out.println (executeupdate); the } - //DeleteWuyi Public voidDelete (Statement stmt)throwsSQLException { the //success-returns false - BooleanExecute = stmt.execute ("Delete from Li Yunchen." Select where study number =11 and course number = 2 "); Wu System.out.println (execute); - } About //Test Cases $ Public Static voidMain (string[] args)throwsexception{ -Dbutil d =Newdbutil (); - //3. Through database connection operation database, realize adding and removing to change the search -Statement stmt =conn.createstatement (); A //ResultSet executeQuery (String sqlString): Executes the SQL statement that queries the database and returns a result set (ResultSet) object. + //D.insert (stmt); the //d.update (stmt); - D.delete (stmt); $ D.select (stmt); the the } the the -}
Java changes to SQL Server additions and deletions