JDBC Connection Database

Source: Internet
Author: User
Tags sql injection

I. Using statement for JDBC database queries

The statement object in JDBC is used to send SQL statements to the database, and to complete the additions and deletions of the database, it is only necessary to send additions and deletions to the database through this object.
The Executeupdate method of the statement object is used to send an increment, delete, and change SQL statement to the database, and after the execution of the executeupdate, an integer is returned (that is, the additions and deletions result in several rows of data in the database).
The Statement.executequery method is used to send a query statement to the database, and the ExecuteQuery method returns the ResultSet object that represents the query result.

(1) Query---Read
 Public classJdbcdemo { Public Static voidMain (string[] args)throwsException {//the database URL to connect toString url = "Jdbc:mysql://localhost:3306/test"; //the user name used when connecting to the databaseString username = "root"; //the password to use when connecting to the databaseString password = "root"; //1. Load Driver//Drivermanager.registerdriver (New Com.mysql.jdbc.Driver ()); It is not recommended to load the driver in this wayClass.forName ("Com.mysql.jdbc.Driver");//It is recommended to use this method to load the driver//2. Get a link to the databaseConnection conn =drivermanager.getconnection (URL, username, password); //3. Get statement for sending SQL statements to the databaseStatement st =conn.createstatement (); String SQL= "Select Id,name,age,email,role,phone from User"; //4. Send SQL to the database and get resultset representing the result setResultSet rs =st.executequery (SQL); //5. Remove data from the result set         while(Rs.next ()) {System.out.println ("Id=" + rs.getobject ("id"))); System.out.println ("Name=" + rs.getobject ("name"))); System.out.println ("Password=" + rs.getobject ("Age")); System.out.println ("Email=" + rs.getobject ("email"))); System.out.println ("Birthday=" + rs.getobject ("role")); System.out.println ("Birthday=" + rs.getobject ("Phone")); }        //6. Close the link and release the resourceRs.close ();        St.close ();    Conn.close (); }}
(2) Insert--create
Statement st == "INSERT into user (...) VALUES (...)" ;   int num =if(num>0) {     System.out.println ("Insert succeeded!!! "); }
(3) Delete--delete
Statement st == "Delete from user where id=1;   int num =if(num>0) {     System.out.println ("Delete succeeded!!! "); }
(4) Update--update
Statement st == "Update user set Name= ' where name= '";  int num =if(num>0) {     System.out.println ("Modified successfully!!! "); }
Two. Using PreparedStatement for JDBC database queries

Preperedstatement is a subclass of statement, and its instance object can be obtained by calling the Connection.preparedstatement () method, As opposed to statement objects: Preperedstatement can avoid problems with SQL injection.
Statement causes the database to compile SQL frequently, potentially causing a database buffer overflow. PreparedStatement can pre-compile SQL to improve the efficiency of database execution. and preperedstatement for parameters in SQL, allowing for substitution in the form of placeholders, simplifying the writing of SQL statements.

 Public classJAVAJDBC { Public Static voidMain (string[] args)throwsclassnotfoundexception, sqlexception{Connection Connection=NULL; PreparedStatement PreparedStatement=NULL; ResultSet ResultSet=NULL; Try {            //1. Load Database driverClass.forName ("Com.mysql.jdbc.Driver"); //2. Get the database link through the Drive management classConnection = Drivermanager.getconnection ("Jdbc:mysql://localhost:3306/test?characterencoding=utf-8", "root", "root" "); //3. Define SQL statements? represents placeholdersString sql = "SELECT * from user where name =?"; //4. Get preprocessing statementPreparedStatement =connection.preparestatement (SQL); //5, set the parameter, the first parameter is the ordinal of the parameter in the SQL statement (starting from 1), the second parameter is the set parameter valuePreparedstatement.setstring (1, "Goshanyi"); //6. Issuing SQL execution query to the database, querying the result setResultSet =Preparedstatement.executequery (); //7. Traverse Query Result set             while(Resultset.next ()) {System.out.println (resultset.getstring ("id") + "" +resultset.getstring ("role"))); }        } Catch(Exception e) {e.printstacktrace (); }finally{            //8. Releasing Resources            if(resultset!=NULL){                Try{resultset.close (); } Catch(SQLException e) {//TODO auto-generated Catch blockE.printstacktrace (); }            }            if(preparedstatement!=NULL){                Try{preparedstatement.close (); } Catch(SQLException e) {//TODO auto-generated Catch blockE.printstacktrace (); }            }            if(connection!=NULL){                Try{connection.close (); } Catch(SQLException e) {//TODO auto-generated Catch blockE.printstacktrace (); }            }        }    }}

JDBC Connection Database

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.