[Database Operations] How to use JDBC in Java.

Source: Internet
Author: User

Objective:
Presumably everyone in the actual code has encountered the operation of JDBC, here only to do their own summary, there are errors and incomplete also ask you to put forward.

1,jdbc actually a set of specifications (interfaces)
Database vendors need to implement this interface (Implementation Class)--database driver


The role of 2,JDBC:
You can create a link to the database
Send SQL statement
Receive return value, process result

3,api detailed (java.sql or javax.sql)

DriverManager class:
manages the basic services of a set of JDBC drivers.
Common methods:
Registerdriver (Driver): Registering drivers
View MySQL Driver with the following code:
    &N Bsp          
        find that the driver has already been registered when the class is loaded, and we only need to load driver into memory at a later time
  class. Class
  object. GetClass ()
  Class.forName ("Fully qualified name (package name + class name)")
  later in development we pass Class.forName ("COM.MYSQL.J Dbc. Driver ") to register the driver in.  
   static Connection getconnection (string url, string user, string password): Get link
  Parameter description:
  URL: Tell JDBC to connect to the database
  fixed format: protocol: Sub-Protocol: Sub-protocol Name parameter
 mysql:jdbc:mysql:// Localhost:3306/databasename
 oracle:jdbc:oracle:thin: @localhost: 1521: Instance name
 user: Login name of the database
 password: Login password for database

  Connection Interface:
Create Statement performer:
Connection conn=drivermanager.getconnection ("Jdbc:mysql://localhost:3306/database", "root", "123456");

Common methods:
Statement createstatement (): Creating a Statement-statement performer
PreparedStatement preparestatement (String sql): Create a precompiled statement execution object
CallableStatement preparecall (String SQL):(understanding) creates a CallableStatement object to invoke the database stored procedure.

  Statement (easy to generate SQL injection, later use PreparedStatement). There will be a blog explaining the problem later.
SQL Statement Performer:
Statement st=conn.createstatement ();

Common methods:
ResultSet executeQuery (String sql): Executes a query statement, returning a collection ☆
int executeupdate (String sql): Performs an update insert DELETE statement that returns the number of rows affected. ☆
Boolean execute (SQL): Executes the given SQL statement, which may return multiple results.
Returns true to execute the query statement
Call Getresultset to get query results
If it returns false, the update insert DELETE statement is performed
Call Getupdatecount to get the number of rows affected

  ResultSet interface
    
Results of the query returned:
String sql = "...";
ResultSet rs=st.executequery (SQL);

    Common methods:
Boolean next (): Determines if there is a record, and moves to the next line
Get content:
GetXXX (parametric)
The notation of the parameter:
1. Field name string
2. The first few columns starting from 1
GetInt ()
GetString ()
GetObject ()

4, example writing of Jdbcutil class
(1) configuration file jdbc.properties

drivername=com.mysql.jdbc.driverurl=jdbc:mysql://localhost:3306/ddatabasenameuser=rootpassword=1234

(2) Jdbcutil.java

 1 Import java.sql.Connection; 2 Import Java.sql.DriverManager; 3 Import Java.sql.ResultSet; 4 Import java.sql.SQLException; 5 Import java.sql.Statement; 6 Import Java.util.ResourceBundle; 7 8 public class Jdbcutil {9//ctrl + SHIFT + X turns into uppercase//ctrl + SHIFT + Y turns into lowercase one static final String drive     rname;12 static final string url;13 static final string username;14 static final string password;15 16 STATIC{17 18/* is specifically used to load the properties file via ResourceBundle resourcebundle bundle=resourcebundle.getbund     Le ("file name"); 20 21 by Bundle.getstring (the name of the key), String value=bundle.getstring ("url"); 23 */24         ResourceBundle bundle=resourcebundle.getbundle ("jdbc"), drivername=bundle.getstring ("drivername"); 27 url=bundle.getstring ("url"), username=bundle.getstring ("user"), password=bundle.getstring ("pas Sword "),}31 static{33 try {Class.fornaMe (drivername); catch (ClassNotFoundException e) {e.printstacktrace (); 37}38}39 40//Get link Connection public static getconnection () throws sqlexception{42 return Drivermanager.getconn Ection (Url,username,password); 43}44 45//Release resources the public static void Closeresource (Connection conn,statemen T St,resultset Rs) {rs!=null) {$ try {rs.close ();             Exception e) {e.printstacktrace ();}53}54 (st!=null) {56 try {st.close (); SQLException} catch (e) {E.printstacktrac E ();}61}62 if (conn!=null) {try {$ conn.close ()      ; SQLException} catch (e) {e.printstacktrace (); 68}69}70 71 }72}

(3) Cruddemo, using the PreparedStatement method

  1 public class Ppcruddemo {2 public static void Main (string[] args) {3//Insert 4//insert ("Zhao Si", "12  3 "," [email protected] ");  5//Update 6//updatebyname ("Zhao Si", "Nicholas Zhao Four");  7//Get 8//getbyname ("Nicholas Zhao IV"); 9//delete Deletebyname ("Nicholas Zhao IV");         One} of the private static void Deletebyname (String string) {14//template Connection Conn=null; 16 PreparedStatement St=null; ResultSet Rs=null;              try {20//Get link conn=jdbcutil.getconnection (); 22//write SQL 23 String sql= "Delete from user where username =?"; 24//Get pre-compiled performer st=conn.preparestatement (SQL); 26//Set parameter St.setstring (1, string); 28//Execute SQL with int i = St.executeupdate (); 30//Processing results if (i>0) {System.out.println ("success");}else{System.out.println ("failure"); \ n} catch (Exception e) {PNS E.print StackTrace (); }finally{39//Release Resources JDBCUTIL.CLOSERESOURCE (Conn, St, RS); 41} 42 4 3} The private static void Getbyname (String string) {Connection conn=null; Prepared Statement St=null; ResultSet Rs=null; try {conn=jdbcutil.getconnection (); sql= String "SELECT * from User W Here username=? Limit 1 "; St=conn.preparestatement (SQL); St.setstring (1, string); Rs=st.executequery (); (Rs.next ()) {System.out.println (Rs.getint (1) + ":" +rs.getstring (2) + ":" +rs.getobject (3) + ":" +rs.getobject (4)); (Exception e) {//Todo:handle Exception E.PRINTSTACKTR Ace ();        64 }finally{Jdbcutil.closeresource (Conn, St, RS); 67} 68 69} 70 71 private static void Updatebyname (String oldname, String newName) {Connection conn=null; Statement St=null; ResultSet Rs=null; try {conn=jdbcutil.getconnection (); sql= String "Update user set User Name =? where username =? "; St=conn.preparestatement (SQL); St.setstring (1, newName); Bayi st.setstring (2, oldname); The i=st.executeupdate int ();                 84//Processing result (i>0) {System.out.println ("success");}else{88 SYSTEM.OUT.PRINTLN ("failure"); Exception} catch (e) {e.printstacktrace ();}finall  y{94 Jdbcutil.closeresource (Conn, St, RS); 95} 96 97        98} The private static void Insert (string username, string password, string email) {101 Connec             tion conn=null;102 preparedstatement st=null;103 ResultSet rs=null;104 try {106 Get links 107 conn=jdbcutil.getconnection (); 108//write sql109 String sql= "INSERT INTO U Ser values (null,?,?,?) "; 110//Get precompiled Statement Performer 111st=conn.preparestatement (SQL); 112//Set parameter 113 St.setstri Ng (1, username); st.setstring (2, password); st.setstring (3, email); 116//Execute SQL11 7 int i=st.executeupdate (); 118//Processing result 119 if (i>0) {SYSTEM.OUT.P RINTLN ("Success"); 121}else{122 System.out.println ("failure"); 123}124} catch (Exce Ption e) {e.printstacktrace () 126}finally{127 Jdbcutil.closeresource (Conn, St, RS); 128}129}130 131} 

There is not much depth here, practice makes perfect, for the time being summed up so much.

[Database Operations] How to use JDBC in Java.

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.