/**/
Import java.sql.*; Public classJdbctest { Public Static voidMain (string[] args) {String user="User1"; String passwd="PWD1"; String Utl="jdbc:mysql://localhost:3306/test"; String Driver="Com.mysql.jdbc.Driver"; Connection Con=NULL; Statement stmt=NULL; ResultSet RS=NULL; Try{ Try{class.forname (driver); } Catch(ClassNotFoundException e) {//TODO auto-generated Catch blockE.printstacktrace (); } con=drivermanager.getconnection (UTL,USER,PASSWD); stmt=con.createstatement (); Stmt.execute ("INSERT INTO Employee values (1, ' James1 ', +)"); Stmt.execute ("INSERT INTO Employee values (2, ' James2 ', +)"); RS=stmt.executequery ("SELECT * from Empolyee");//accessing result set SQL Objects while(Rs.next ()) {System. out. println (Rs.getint (1)+""+rs.getstring (2)+""+rs.getint (3)); } } Catch(SQLException E1) {e1.printstacktrace (); }finally{ Try{ if(rs!=NULL) Rs.close (); if(stmt!=NULL) Stmt.close (); if(con!=NULL) Con.close (); }Catch(SQLException e) {System. out. println (E.getmessage ()); } } }}
Operation Steps
- Load the JDBC drive and load the JDBC driver into the classpath.
- Load the JDBC driver and register it in DriverManager. General use of reflection mechanism Class.forName (String drivername)
- Establish database connection, get Connection object. Typically implemented through the Drivermanager.getconnection (url,username,passwd) method, where the URL represents a string that connects to the database, Uaername represents the user name of the connection database, and passwd represents the password for the connection database.
- Establishes a statement object or Preparestatement object.
- Executes the SQL statement.
- Accesses the structure set ResultSet object.
- Access resultset, Statement, PreparedStatement, and connection objects down, freeing up the resources that are occupied.
accessing MySQL with JDBC