JDBC--001--General way to create a database connection (ORACLE/MYSQL)

Source: Internet
Author: User

To connect to a database step:
1. Registration driver (only once)
2. Establishing a connection (Connection)
3. Create a statement that executes SQL (Statement)
4. Execute the statement
5. Processing execution Results (RESULTSET)
6. Releasing Resources
Example:
Public voidConnectionoracle ()throwssqlexception{Connection conn =NULL; // database connection PreparedStatement PS =NULL; // Precompiled Statement Object ResultSet rs =NULL; // result set object Try { //Registering (Loading) Oracle Drivers class.forname ("Oracle.jdbc.driver.OracleDriver");
Class.forName ("Com.mysql.jdbc.Driver");register (load) MySQL driver
String url = "JDBC:ORACLE:THIN:@127.0.0.1:1521:ORCL";
String url = "Jdbc:mysql://127.0.0.1:3306/mybatis";
String url = "Jdbc:mysql://localhost:3306/mybatis";
String User= "Scott"; String Password= "Tiger"; Conn = drivermanager.getconnection (url, user, password); String SQL= "Select ename from emp where job = ' Clerk '"; PS=conn.preparestatement (SQL); RS=Ps.executequery (); while(Rs.next ()) {System.out.println ("Ename is:" + rs.getstring ("ename")); } System.out.println ("[Email protected]@@"); } Catch(ClassNotFoundException e) {e.printstacktrace (); }finally {
try {if (rs! = null) {Rs.close ();}}
finally {
try {if (PS! = null) {Ps.close ();}}
finally {if (conn! = null) {Conn.close ();}
}
}
}
}
If sql= "SELECT COUNT (*) from items";
When it is used
while (Rs.next ()) {
System.out.println (Rs.getint (1));
}

JDBC--001--General way to create a database connection (ORACLE/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.