Database connection and operation data of JDBC database programming

Source: Internet
Author: User
Tags garbage collection stmt

JDBC: The full name of the Java database Connectivity Java databases connection.

Initially, based on the development of a database product, it is necessary to understand the API of a database. Programming with direct access to a database's interface through C + +. However, cross-database platform development is not possible.
Later, cross-platform development was achieved through a unified database interface, such as Odbc,ado.net. JDBC is the unified interface for Java to access the database platform.
The porting of JDBC to different database platforms is not complete.
JDBC is a unified interface for the Java program at one end. It is not uniform for the database product connection end. (provided by the manufacturer)

SQL six major statements:

Select

Select * from T where ...

Insert

Insert into T values (...)

Create

Create table T (...)

Delete

Delete from T where ...

Update

Update T set t1= ... and t2= ...

Drop

Drop Table T

JDBC connection to SQL SERVER

1 Add database product related class library. (Database driver package). Configuring environment variables for driver packages (ClassPath)

MyEclipse: Project right mouse button Project->properties->java Build path->libraries->add External jars-> Find SQLJDBC4 Load

Why put a database driver package into a project instead of the entire system?
Put into the system, the project and the project will have an impact, different versions of the jar package will create a conflict

2 Registration to DriverManager

DriverManager: Basic service for managing databases, to connect to a database, you need to register with DriverManager. (Autoenrollment when instantiated)

3 Connecting database objects

ImportJava.sql.*;/*** JDBC Connection SQL SERVER * 2014-5-5 *@authorAdministrator*/ Public classDemo1 { Public Static voidMain (string[] args)throwsException {//1 Add Database product related class library. //2 registration to DriverManager. (autoenrollment when instantiated)//Class is Java.lang in the package, calling method Forname, creating an instance from the stringClass.forName ("Com.microsoft.sqlserver.jdbc.SQLServerDriver"); //new Com.microsoft.sqlserver.jdbc.SQLServerDriver (); //3 Connecting database objects        ////Jdbc:sqlserver://IP Address: port; databasename= database Name ", account number, passwordString url= "Jdbc:sqlserver://183.33.129.192:1433;databasename=javastu"; Connection Conn=drivermanager.getconnection (URL, "sa", "qsnprac157"); System.out.println ("Connection Database succeeded"); } }

Execute Query SQL statement

1 Creating a statement object from a connection

2 executing a query SQL statement from a statement object, returning a result set

3 loop to get result set contents

4 Close the resource (open first off)

ImportJava.sql.*;/*** Connect to database and Execute query statement (unreasonable version) * 2014-5-5 *@authorAdministrator **/ Public classDemo2 { Public Static voidMain (string[] args, string Sno, String Ssex)throwsexception{//Add a driver package//RegisterClass.forName ("Com.microsoft.sqlserver.jdbc.SQLServerDriver"); //ConnectionString url= "Jdbc:sqlserver://113.76.233.233:1433;databasename=stumanage"; String User= "SA"; String Password= "qsnprac157"; Connection Conn=drivermanager.getconnection (URL, user, password); //Create Statement object (function: Send SQL statement to database)Statement stmt =conn.createstatement (); //executes the given SQL statement and returns the result set to the ResultSet objectResultSet rs=stmt.executequery ("SELECT * from Student"); //looping through a result set         while(Rs.next ()) {System.out.println (Rs.getint ("Sage")); System.out.println (Rs.getstring ("Ssex")); }        //Close ResourceRs.close ();        Stmt.close ();           Conn.close (); }}

DriverManager class: Basic services for managing drivers (deleting, locating, registering drivers, establishing database connections, getting, updating logs, setting)

Connection interface: Connection to a specific database (session). Executes the SQL statement in the connection context and returns the result

Statement interface: Executes a static SQL statement and returns the object to which it produces results.

ResultSet interface: A data table that represents a database result set, typically generated by executing statements that query the database.

The problem with the previous code: If an exception occurs during traversal, the resource cannot be shut down, accumulated gradually, and a large amount of memory is occupied.

Importjava.sql.Connection;ImportJava.sql.DriverManager;ImportJava.sql.ResultSet;Importjava.sql.SQLException;Importjava.sql.Statement;/*** Connect to database and Execute query statement (perfect version) * 2014-5-5 *@authorAdministrator **/ Public classDemo3 { Public Static voidMain (string[] args, string Sno, String Ssex) {Connection conn=NULL; Statement stmt=NULL; ResultSet RS=NULL; //Add a driver package        Try{            //RegisterClass.forName ("Com.microsoft.sqlserver.jdbc.SQLServerDriver"); //ConnectionString url= "Jdbc:sqlserver://113.76.233.233:1433;databasename=stumanage"; String User= "SA"; String Password= "qsnprac157"; Conn=drivermanager.getconnection (URL, user, password); //Create Statement object (function: Send SQL statement to database)stmt =conn.createstatement (); //executes the given SQL statement and returns the result set to the ResultSet objectRs=stmt.executequery ("SELECT * from Student"); //looping through a result set             while(Rs.next ()) {System.out.println (Rs.getint ("Sage")); System.out.println (Rs.getstring ("Ssex")); }        }Catch(ClassNotFoundException e) {e.printstacktrace (); }Catch(SQLException e) {e.printstacktrace (); }        finally{            Try{                //Close Resource                if(rs!=NULL){//determine if initialization is successful (uninitialized will report an exception)Rs.close (); RS=NULL; }                if(stmt!=NULL) {stmt.close (); //Recycle operating system resourcesstmt=NULL;//garbage collection mechanism reclaims memory resources                }                if(conn!=NULL) {conn.close (); Conn=NULL; }            }Catch(SQLException e) {e.printstacktrace (); }        }    }}

Java has a garbage collection mechanism, why use the Close () method to recycle garbage

The garbage collection mechanism can only reclaim memory resources. Other resources (IO devices, processes, CPUs, etc.) that need to be explicitly released

ImportJava.sql.*;/*** Connect to database and update data *@authorAdministrator **/ Public classDemo4 { Public Static voidMain (string[] args) {Connection conn=NULL; Statement stmt=NULL; //Add Driver//Register        Try{class.forname ("Com.microsoft.sqlserver.jdbc.SQLServerDriver"); //ConnectionString url= "Jdbc:sqlserver://113.76.113.84:1433;databasename=javastu"; String User= "SA"; String Password= "qsnprac157"; Conn=drivermanager.getconnection (URL, user, password); //To Create a statement objectstmt=conn.createstatement (); //Update (Add, modify, delete) data to a tableString sql= "INSERT into Student values (' 1202020001 ', ' CW ', 20)"; //String sql2= "Delete from Student where sname= ' cw '"; //String sql3= "Update Student set sname= ' CW ' where sno=1202020002";stmt.executeupdate (SQL); }Catch(ClassNotFoundException e) {e.printstacktrace (); }Catch(SQLException e) {e.printstacktrace (); }        //Close Resource        finally{            Try{                if(stmt!=NULL) {stmt.close (); stmt=NULL; }                if(conn!=NULL) {conn.close (); Conn=NULL; }            }Catch(SQLException e) {e.printstacktrace (); }        }    }}

Reference: Still Academy horse soldier Video Tutorial.

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.