Java database Connection and considerations

Source: Internet
Author: User
Tags sql injection

Jdbc:java database connection, which is the Java connection.
Function: Completes the interaction between the database data and the memory data.

In order to block differences between different databases, an interface standard has been established between the memory and the various databases. Each vendor implements the interface class according to the standard of the interface.


JDBC is a standard set of Java connection databases. The standard defines a series of interfaces, which are provided by the database vendor in accordance with the characteristics of its own database, which is called by the developer. Developers can block differences between different database vendors based on the interface invocation method. In this way, whatever database is connected is a set of APIs.

JDBC Operation steps: Flow operation steps:
① load driver, establish connection 1, establish flow
② Execute SQL Statement 2, Operation Flow
③ close Connection 3, close

SQL injection: When the SQL statement is executed, because the value of the SQL statement is input by the user, it is received as a variable, if the SQL statement is executed in a concatenation string, if there are illegal characters or keywords in the data, it can result in a syntax error, or the execution result is incorrect, this is called SQL injection.


The difference between statement and PreparedStatement:

Statement is the parent interface of PreparedStatement. When executing SQL statements, you can only stitch the values in a concatenation string. will cause SQL injection. and low efficiency.

PreparedStatement, which is a precompiled SQL statement execution object that supports placeholder mode, does not cause SQL injection, regardless of the value of the data, when the string is processed. and high efficiency.

To illustrate:

 Packagedatabase connection;Importjava.sql.Date;/*** Citizen entity class *@authorC **/ Public classManbean {/**Citizen Number*/    Private intID; /**name*/    PrivateString name; /**Sex*/    PrivateString sex; /**Birthday*/    PrivateDate Briyhday;  Public intgetId () {returnID; }     Public voidSetId (intID) { This. ID =ID; }     PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     PublicString Getsex () {returnsex; }     Public voidsetsex (String sex) { This. Sex =sex; }     PublicDate Getbriyhday () {returnBriyhday; }     Public voidSetbriyhday (Date briyhday) { This. Briyhday =Briyhday; }     PublicManbean (string name, string sex, Date briyhday) {Super();  This. Name =name;  This. Sex =sex;  This. Briyhday =Briyhday; }     PublicManbean () {Super(); //TODO auto-generated Constructor stub} @Override PublicString toString () {return"Manbean [id=" + ID + ", name=" + name + ", sex=" + Sex + ", briyhday=" + Briyhday + "]\n"; }    }

Stress: If you define a surrogate construct in a class then there is no default no-no-no-no structure, so you have to add a no-no-no-no.

  

Importjava.sql.Connection;ImportJava.sql.DriverManager;Importjava.sql.PreparedStatement;ImportJava.sql.ResultSet;Importjava.sql.SQLException;/*** All DAO parent class * *@authorC **/ Public classMandao {/**Connection Object*/    protectedConnection con =NULL; /**SQL statement Execution Object*/    protectedPreparedStatement PR =NULL; /**result Set Object*/    protectedResultSet rs =NULL; /*** Link Creation*/     Public voidsetcnnonection () {//Load Driver        Try{class.forname ("Com.mysql.jdbc.Driver"); //Establish a connection//JDBC indicates that a connection needs to be established using JDBC. MySQL indicates the connection database type, localhost indicates the IP address of the connection server//where localhost is the native IP//3306 represents the port number of MySQL, Mytest1 is the database name in SQL, which indicates that the database tables in the class need to be used//Characterencoding=utf-8 to set the encoding set of the connected databasecon = drivermanager.getconnection ("Jdbc:mysql://localhost:3306/mytext1?characterencoding=utf-8", "root",                    "123456"); } Catch(Exception e) {//TODO auto-generated Catch blockE.printstacktrace (); }    }    /*** Close Stream*/     Public voidcloseconnecting () {Try {            if(rs! =NULL) {                 This. Rs.close (); }             This. Pr.close ();  This. Con.close (); } Catch(Exception e) {//TODO auto-generated Catch blockE.printstacktrace (); }    }     Public Static voidMain (string[] args) {Mandao m=NewMandao ();    M.setcnnonection (); }}

Emphasis: the establishment of connections and the closure of the exile in a class to define two methods is an abstract behavior, convenient to use the time to call its methods directly, without writing duplicate code.

 Packagedatabase connection;Importjava.sql.Connection;Importjava.sql.Date;ImportJava.sql.DriverManager;Importjava.sql.PreparedStatement;ImportJava.sql.ResultSet;Importjava.sql.SQLException;Importjava.util.ArrayList;Importjava.util.List;/*** Citizen Persistent Word implementation interface *@authorC **/ Public classMandaoimplextendsMandaoImplementsImandao { Public voidAdd (Manbean man) {//Load Driver        Try {             This. Setcnnonection (); //Execute SQL statement,? Represents a placeholder, you need to fill the placeholder with dataPr=Con.preparestatement ("INSERT into T_man (manname,sex,brithday) VALUES (?,?,?)"); //takes the name attribute from the man object and fills the first placeholderPr.setstring (1, Man.getname ()); Pr.setstring (2, Man.getsex ()); Pr.setdate (3, Man.getbriyhday ()); //Update database must be writtenpr.executeupdate (); } Catch(Exception e) {e.printstacktrace (); }finally{             This. closeconnecting (); }    }    /*** Find all citizens Object Collection*/     PublicList<manbean>FindAll () {List<ManBean> list =NewArraylist<manbean>(); Try {             This. Setcnnonection (); PR= Con.preparestatement ("Select *from T_man"); //performs a query operation that encapsulates the data queried by the SQL statement in the result set objectrs =Pr.executequery (); //Sets a pointer to a result set, pointing to the next record, if the method returns false, indicating that the pointer is to the end of the result set.              while(Rs.next ()) {Manbean man=NewManbean (); //takes the value of the ID column in the database out, populating the ID property of the Entity object. "" is the name of the column nameMan.setid (Rs.getint ("id")); Man.setname (Rs.getstring ("Manname")); Man.setsex (Rs.getstring ("Sex")); Man.setbriyhday (Rs.getdate ("Brithday")); //joins the encapsulated record entity object to the collectionList.add (man); }        } Catch(Exception e) {//TODO auto-generated Catch blockE.printstacktrace (); } finally {             This. closeconnecting (); }        returnlist; }

emphasis: 1, add, delete, modify must be done after The executeupdate () method updates the database. 2, the query uses the result set to pass the database data. 3, the connection must be closed at the end, otherwise it will result in loss of data.

  

Java database Connection and considerations

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.