Java JDBC Connection MySQL

Source: Internet
Author: User
Tags exception handling

    1. Download the driver package: http://dev.mysql.com/downloads/connector/j/, extract the jar files, such as Mysql-connector-java-8.0.11.jar
    2. Create a new folder under the project, put the jar package in, click on the project right, "build path"--"Configure Build Path", add Jar file
    3. Connecting to a database
    4. Bold section for new features
  • 1  Public Final classDbconn2 {3      Public StaticConnection getconn ()4     {5Connection conn =NULL;6         7String Driver = "Com.mysql.cj.jdbc.Driver";8String user = "root";9String passwd = "root";TenString URL = "JDBC:MYSQL://LOCALHOST:3306/STORE?USESSL=FALSE&SERVERTIMEZONE=UTC";//Specify the database store to access One          A         //driver is loaded -         Try -         { the Class.forName (driver); -conn =drivermanager.getconnection (URL,USER,PASSWD); -}Catch(SQLException e) -         { + e.printstacktrace (); -         } +         Catch(classnotfoundexception e) A         { at e.printstacktrace (); -         } -         returnConn; -     } -  -}
    1  Public Final classdbclose2 {3     /**4 * Close Add feature resource5      * @paramPstmt,rs,conn6      */7          Public Static voidAddclose (PreparedStatement pstmt, Connection conn)8         {9             /*Ten * Multiple Try-catch starting points: safety One              */ A             Try -             { -                 if(Pstmt! =NULL) the                 { - pstmt.close (); -                 } -}Catch(SQLException E1) +             { - e1.printstacktrace (); +             } A             Try at             { -                 if(Conn! =NULL) -                 { - conn.close (); -                 } -}Catch(SQLException e) in             { - e.printstacktrace (); to             } +         } -          the         /** * * Close Resources $          * @paramPstmt,rs,connPanax Notoginseng          */ -          Public Static voidQueryClose (PreparedStatement pstmt, ResultSet RS, Connection conn) the         { +             Try A             { the                 if(Pstmt! =NULL) +                 { - pstmt.close (); $                 } $}Catch(SQLException E1) -             { - e1.printstacktrace (); the             } -             TryWuyi             { the                 if(rs! =NULL ) -                 { Wu rs.close (); -                 } About}Catch(SQLException E1) $             { - e1.printstacktrace (); -             } -             Try A             { +                 if(Conn! =NULL) the                 { - conn.close (); $                 } the}Catch(SQLException e) the             { the e.printstacktrace (); the             } -         } in          the}

    Test the code. To test if the connection is successful:

  • 1  Public classShow {2 3      Public Static voidMain (string[] args) {4         //declaring connection Objects5 Connection con;6         //driver name7String Driver = "Com.mysql.cj.jdbc.Driver";8         //the URL points to the database name you want to access MyData9String url = "JDBC:MYSQL://LOCALHOST:3306/STORE?USESSL=FALSE&SERVERTIMEZONE=UTC";Ten         //user name when MySQL is configured OneString user = "root"; A         //password for MySQL configuration -String password = "root"; -         //traversing query result sets the         Try { -             //Load Driver - Class.forName (driver); -             //1.getConnection () method, connect MySQL database!!  +Con =drivermanager.getconnection (Url,user,password); -             if(!con.isclosed ()) +SYSTEM.OUT.PRINTLN ("Succeeded connecting to the database!"); A             //2. Create the statement class object to execute the SQL statement!!  atStatement Statement =con.createstatement (); -             //the SQL statement to execute -String sql = "SELECT * from goods where gid= ' g231 '"; -             //3.ResultSet class, used to store the obtained result set!!  -ResultSet rs =statement.executequery (SQL); -System.out.println ("-----------------"); inSystem.out.println ("The execution results are as follows:");  -System.out.println ("-----------------");  toSystem.out.println ("name" + "\ T" + "quantity");  +System.out.println ("-----------------");  -               theString Gname =NULL; *String Gnum =NULL; $              while(Rs.next ()) {Panax Notoginseng                 //get stuname This column of data -Gname = rs.getstring ("Gname"); the                 //get stuid This column of data +Gnum = rs.getstring ("Gnum"); A  the                 //Output Results +System.out.println (gname + "\ T" +gnum); -             } $ rs.close (); $ con.close (); -}Catch(ClassNotFoundException e) { -             //database-driven class exception handling theSystem.out.println ("Sorry,can ' t find the driver!");  - E.printstacktrace (); Wuyi}Catch(SQLException e) { the             //database connection failure exception handling - E.printstacktrace ();  Wu}Catch(Exception e) { -             //Todo:handle Exception About e.printstacktrace (); $}finally{ -SYSTEM.OUT.PRINTLN ("Database data successfully obtained!! "); -         } -     } A  +}

Java JDBC Connection MySQL

Related Article

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.