Java Database connection and query

Source: Internet
Author: User

9 Steps:

1, load the database driver;

2, connect the database;

3, create statement;

5, create SQL syntax string;

6, implementation;

7, if step 6 is to perform new, modify, delete operation then return the number of rows affected, if you are performing a query operation, then step 8:

8, analytic result set resultset;

9. Close the result set resultset, close the statement, and close the database connection.

On the code:

     Public Static voidMain (string[] args)throwsSQLException {Try{class.forname ("Com.mysql.jdbc.Driver"); } Catch(ClassNotFoundException e) {System.out.println ("Driver class not found!" ");        E.printstacktrace (); } String URL= "Jdbc:mysql://localhost:3306/exe_course"; String UserName= "Root"; String Password= "123456"; Try(Connection Connection =drivermanager.getconnection (URL, userName, password)) {System.out.println ("The database link was successful!" "); Try(Statement Statement =connection.createstatement ()) {String command= "INSERT into a_dept (name) VALUES (' 1 '), (' 2 ')"; intCount =statement.executeupdate (command); System.out.println (Number of affected rows: +count); String Selectsql= "SELECT * FROM A_dept"; Try(ResultSet ResultSet =statement.executequery (Selectsql)) {                     while(Resultset.next ()) {System.out.println (Resultset.getint ("id")); System.out.println (Resultset.getstring ("Name")); }                }            }        }    }

The above code uses two usages of try, and it is recommended to use the second usage when you need to release resources, which automatically shuts down resources after the end of use.

Here is the result of the operation:

Java Database connection and query

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.