"Java" JDBC Database connection

Source: Internet
Author: User
Tags stmt

"What is it?"

JDBC Full name javadatabaseconnectivity, a Java database connection, is a Java API that executes SQL statements. Programmers can connect to a relational database through JDBCAPI and use Structured query statements (that is, SQL) to complete queries and updates to the database.

Role

In short, JDBC can do three things: establish a connection to the database, send a statement that operates the database, and process the results. The following code snippet gives a basic example of the above three steps (it is too classic to be intercepted directly from the encyclopedia):

1. Establish a connection to the database:

Connection con = drivermanager.getconnection ("Jdbc:odbc:wombat", "Login", "password");

2. Send the statement of the operational database:

Statement stmt = Con.createstatement (); ResultSet rs =stmt.executequery ("Select a, B, C from Table1");

3. Processing of return results:

while (Rs.next ()) {     int x = Rs.getint ("a");     String s = rs.getstring ("b");     float f = rs.getfloat ("C");}

" JDBC Connect Data Instance "

need to introduce the appropriate driver Jar package, Mysql-connector-java-5.1.26-bin.jar, download online.

Sys-config.xml configuration File Code :    

<?xml version= "1.0" encoding= "UTF-8"?><config><db-info><driver-name> Com.mysql.jdbc.driver</driver-name><url>jdbc:mysql://localhost:3306/drp?characterencoding=utf-8 </url><user-name>root</user-name><password>123456</password></db-info>< /config>

Xmlconfigreader.java class is used to parse the configuration file:

Package Com.bjpowernode.drp.util;import Java.io.inputstream;import Org.dom4j.document;import  Org.dom4j.documentexception;import org.dom4j.element;import org.dom4j.io.saxreader;/** * parsing sys-config.xml files using a singleton mode * * @author Happy * */public class Xmlconfigreader {//lazy (lazy load lazy) private static Xmlconfigreader instance = null;//Save Jdb C Related configuration information private jdbcconfig jdbcconfig = new Jdbcconfig ();p rivate xmlconfigreader () {Saxreader reader = new Saxreader (); INP Utstream in = Thread.CurrentThread (). Getcontextclassloader (). getResourceAsStream ("Sys-config.xml"); try {Document doc = Reader.read (in);//Get JDBC-related configuration information Element Drivernameelt = (Element) doc.selectobject ("/config/db-info/driver-name" ); Element Urlelt = (Element) doc.selectobject ("/config/db-info/url"); Element Usernameelt = (Element) doc.selectobject ("/config/db-info/user-name"); Element Passwordelt = (Element) doc.selectobject ("/config/db-info/password");//Set JDBC-related configuration Jdbcconfig.setdrivername (Drivernameelt.getstringvalue ()); Jdbcconfig.seturl (UrleLt.getstringvalue ()); Jdbcconfig.setusername (Usernameelt.getstringvalue ()); Jdbcconfig.setpassword ( Passwordelt.getstringvalue ()); System.out.println ("read jdbcconfig-->>" + jdbcconfig);} catch (Documentexception e) {e.printstacktrace ();}} public static synchronized Xmlconfigreader getinstance () {if (instance = = null) {instance = new Xmlconfigreader ();} return instance;} /** * Returns JDBC-related configuration * * @return */public jdbcconfig getjdbcconfig () {return jdbcconfig;}}

Other analytic ways See blog: http://blog.csdn.net/u013036274/article/details/52506721

Connectionmanager.java class is used to encapsulate some Connection Method:

Package Com.bjpowernode.drp.util;import Java.sql.connection;import Java.sql.drivermanager;import Java.sql.resultset;import java.sql.sqlexception;import java.sql.statement;/** * with threadlocal package connection * * @author Administrator * */public class ConnectionManager {private static threadlocal<connection> Connectionholder = new THR Eadlocal<connection> ();/** * Get Connection * * @return */public static Connection getconnection () {//Get Conne from thread variables first  Ctionconnection conn = Connectionholder.get ()//if the corresponding connectionif is not bound in the current thread (conn = = null) {try {jdbcconfig jdbcconfig = Xmlconfigreader.getinstance (). Getjdbcconfig (); Class.forName (Jdbcconfig.getdrivername ()); conn = Drivermanager.getconnection (Jdbcconfig.geturl (), Jdbcconfig.getusername (), Jdbcconfig.getpassword ());//Set Connection to Threadlocalconnectionholder.set (conn);} catch (ClassNotFoundException e) {e.printstacktrace (); throw new ApplicationException ("System error, contact system Administrator"); SQLException e) {e.printstacktrace (); throw new ApplicatIonexception ("System error, please contact system Administrator");}} Return conn;}  /** * Turn off Connection */public static void CloseConnection () {Connection conn = Connectionholder.get (); if (conn! = null) {try {conn.close ();//Clear Connectionconnectionholder.remove () from Threadlocal;} catch (SQLException e) {e.printstacktrace ();}}} public static void Close (Connection conn) {if (conn! = null) {try {conn.close ();} catch (SQLException e) {E.printstacktrac E ();}}} public static void Close (Statement pstmt) {if (pstmt! = null) {try {pstmt.close ();} catch (SQLException e) {e.printstacktr Ace ();}}} public static void Close (ResultSet rs) {if (rs! = null) {try {rs.close ();} catch (SQLException e) {e.printstacktrace ()}} }public static void BeginTransaction (Connection conn) {try {if (conn! = null) {if (Conn.getautocommit ()) {Conn.setautocomm It (false); Manual Commit}}} catch (SQLException e) {}}public static void CommitTransaction (Connection conn) {try {if (conn! = null) {if (!c Onn.getautocommit ()) {Conn.commit ();}}} catch (SQLException e) {}}public static void RollbackTransaction (Connection conn) {try {if (conn! = null) {if (!conn.getautocommit ()) {Conn.rollback ();}}} catch (SQLException e) {}}}

Add:

Oracle The connection:

    DriverClass:oracle.jdbc.driver.OracleDriver     Url:jdbc:oracle:thin: @localhost: 1521:ORCL

Summary

But is it a hassle to configure the connection every time? What if it's more than one project? When there are many similar transactions, it is necessary to abstract and abstract the common place into a higher level interface class. So the following blog to introduce the connection pool.

"Java" JDBC Database connection

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.