accessing MySQL with JDBC

Source: Internet
Author: User

/**/
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

  1. Load the JDBC drive and load the JDBC driver into the classpath.
  2. Load the JDBC driver and register it in DriverManager. General use of reflection mechanism Class.forName (String drivername)
  3. 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.
  4. Establishes a statement object or Preparestatement object.
  5. Executes the SQL statement.
  6. Accesses the structure set ResultSet object.
  7. Access resultset, Statement, PreparedStatement, and connection objects down, freeing up the resources that are occupied.

accessing MySQL with JDBC

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.