To create a JDBC application:
We take the Mylibray authors table in the MySQL authoritative guide as an example
Here are six steps to build a JDBC application:
Import the packet. You need to include packages that contain JDBC classes that require database programming. In most cases, you can use the import java.sql.*
Register the JDBC driver. You need to initialize the driver to open a communication channel with the database
Open the connection. You need to use the Drivermanager.getconnection () method to create a connection object that represents the physical connection to the database
Executes the query. You need to create and submit an SQL statement to the database using the type Declaration object
Extracts data from the result set. Requires appropriate data about the Resultset.getxxx () method to retrieve the result set
Clean up the environment. Need to explicitly shut down all database resources relative to the JVM's garbage collection
PackageJdbcdemo;ImportJava.sql.*; Public classFirstexample {//JDBC driver name and database address Static FinalString jdbc_driver = "Com.mysql.jdbc.Driver"; Static FinalString Db_url = "Jdbc:mysql://localhost/mylibrary"; //Database Login Verification Static FinalString USER = "root"; Static FinalString PASS = "123456"; Public Static voidMain (string[] args) {Connection conn=NULL; Statement stmt=NULL; Try{ //STEP 2: Register database driverClass.forName ("Com.mysql.jdbc.Driver"); //STEP 3: Open the connectionSYSTEM.OUT.PRINTLN ("Connect database ..."); Conn=drivermanager.getconnection (Db_url,user,pass); //Step 4: Execute a querySYSTEM.OUT.PRINTLN ("Create statement ..."); stmt=conn.createstatement (); String SQL; SQL= "Select Authid,authname,ts from Authors"; ResultSet RS=stmt.executequery (SQL); //STEP 5: Extracting data from the result set while(Rs.next ()) {//get data based on column name intid = rs.getint ("AuthID"); String AuthName= Rs.getstring ("AuthName"); String TS= rs.getstring ("ts"); //Show DataSystem.out.print ("ID:" +ID); System.out.print (", AuthName:" +authname); System.out.print (", TS:" +ts); System.out.println (); } //STEP 6: Clean up the environmentRs.close (); Stmt.close (); Conn.close (); }Catch(SQLException se) {//Handling JDBC ExceptionsSe.printstacktrace (); }Catch(Exception e) {//handling Class.foname () ExceptionsE.printstacktrace (); }finally{ //The finally block is responsible for closing the resource Try{ if(stmt!=NULL) Stmt.close (); }Catch(SQLException se2) {}Try{ if(conn!=NULL) Conn.close (); }Catch(SQLException se) {se.printstacktrace (); }} System.out.println ("Good-bye!");}}
Code
JDBC Basic Learning (i) first JDBC sample code