JDBC in Java detailed implementation configuration file Access database __ Database

Source: Internet
Author: User

JDBC is the specification of the Java Operational database, which actually defines a set of standard database interfaces that must be implemented in order to implement the database through Java operations, and different database vendors provide implementations of the JDBC interface, These specific implementations are packaged into a jar package (that is, database driven) that we use directly when we develop.
Main interfaces in the JDBC API:
First: Driver interfaceIs the interface that all JDBC programs must implement, which is specifically provided to the database vendor for use, and defines the driven style
Second: DriverManagerUsed to load the JDBC driver and create a connection to the database
There are two important ways to do this:
1 drivermanager.registerdriver (Driver Driver)//For registering the given JDBC driver to DriverManager
2 drivermanager.getconnection (string URL, string user, string pwd)//establishes a connection to the database, returning the Connection object representing the connection
Third: Connection interfaceThe main methods are three
1. connection.createstatement (); Create a statement object, static SQL statement query
2. Connection.preparestatement (String sql); Create a PreparedStatement object to implement a dynamic SQL statement query
3. Connection.preparecall (String sql); Create a CallableStatement object to invoke the database stored procedure
Fourth: statement interfaceUse to perform query return query results
1 statement.execute (String sql); Executes various SQL statements, returns a Boolean value, and True indicates that the executed SQL statement has the query results and can be obtained by the Statement.getresultset () method
2 statement.executeupdate (String sql); Executes the insert/update/delete statement in SQL, returning an int value representing the number of records affected
3 statement.executequery (String sql); Executes the SELECT statement in SQL, returning a ResultSet object that represents the result of the query
Fifth: ResultSet interfaceActions for Query Results
1 Resultset.next (); Move the cursor from the current position to the next line
2 resultset.getstring (String columnName); Gets the string type value of the specified field
3 resultset.getstring (int columnindex); Gets the string type value of the specified index
4 resuleset.previous (); Move the cursor from the current position to the previous line

JDBC Operations Database general steps
Registration driver (only once)
Establish connection (Connection)
Create Execute SQL statement (Statement)
Execute statement and Process execution results ( ResultSet)
Free resources

Import java.sql.Connection;
Import Java.sql.DriverManager;
Import java.sql.PreparedStatement;
Import Java.sql.ResultSet;

Import java.sql.SQLException; Here the test is the MySQL database named test; Table is user; Table fields have ID, name, age, salary public class Jdbctest {public static void main (string[] args) {//Step one: Register the driver first,
        Drive typically registers only one try {class.forname ("com.mysql.jdbc.Driver"); catch (ClassNotFoundException e) {//TODO auto-generated catch block System.out.println ("Driver not found
            Order class, load driven failure ");
        E.printstacktrace (); //Step Two: Establish connection connect, set URL, username, password//URL format: JDBC: Sub-Protocol: Sub-name/host name: Port/Database name. Property name = attribute value/...//Note that the URL must not add extra space, otherwise there will be an error, Usessl=false is to resolve the issue of the warning when authentication//String URL = "Jdbc:mysql://lo Calhost:3306/test? "+" user=root&password=wsw011152&useunicode=true&characterencoding=utf-8&
        Usessl=false ";
        String url = "Jdbc:mysql://localhost:3306/test?usessl=false"; String name = "root";
        String PSW = "root";
        Connection connect = null;
            try {connect = drivermanager.getconnection (URL, name, PSW);
        Connect = drivermanager.getconnection (URL);
            catch (SQLException e) {//TODO auto-generated catch block System.out.println ("Database connection failed");
        E.printstacktrace (); //Step Three: Create a Statement, generally recommended to use PreparedStatement//1, execute static SQL statements.
        Typically implemented through statement instances. 2, execute dynamic SQL statements.
        Typically implemented through PreparedStatement instances. 3, execute the database stored procedure.
        Typically implemented through CallableStatement instances.
        String sql = "SELECT * from user where id =?";
        String sql = "SELECT * from user where id =?";
            try {preparedstatement PS = connect.preparestatement (SQL); Ps.setint (1, 1);
            Set the parameters//Fourth step: Execute the statement, get a result set, deal with the results obtained ResultSet result = Ps.executequery ();
          while (Result.next ()) {System.out.println (Result.getint ("id"));      System.out.println (result.getstring ("name"));
                System.out.println (Result.getint ("Age"));
            System.out.println (result.getstring ("salary"));
            //Step Fifth: Close resource result.close ();
            Ps.close ();
        Connect.close ();
        catch (SQLException e) {//TODO auto-generated catch block E.printstacktrace (); }
    }
}

let's explain why JDBC recommends using PreparedStatement instead of statement
First, Java provides three ways to execute SQL statements
CallableStatement; a query that is primarily used for stored procedures.
Statement is primarily used for general purpose queries that are suitable for one-time access to a database, and use it to generate an execution plan for each SQL statement, even if the two statements have only a different parameter.
PreparedStatement: Mainly used for parameterized query, will pass parameters, repeated query

PreparedStatement relative to the advantages of statement in the following points:

1. Using PreparedStatement, the database system compiles SQL statements (requiring JDBC drivers to support precompiled SQL queries) for preprocessing, a preprocessed SQL query that can be reused in future queries. Saves the time to create an execution plan and reduces the overhead of the system, so it is faster than statement queries.
such as queries using statement for the following two sentences, two execution plans are generated, 1000 queries generate 1000 execution plans, and the build execution plan consumes resources, and the
Select Colume from table where colume=1; The
Select Colume from table where colume=2;
But with PreparedStatement, the system compiles the SQL statements, generates only 1 execution plans, and 1000 such queries do not produce an execution plan that is reused by the same query statement below, greatly increasing the speed. The
Select Colume from table where colume=.;
PreparedStatement. Setint (1, 1);
PreparedStatement. Setint (1, 2);
2. You can write dynamically parameterized queries with PreparedStatement you can write SQL query statements with parameters, using the same SQL statements and different parameter values to make a query

3. PreparedStatement can prevent SQL injection attacks, more secure
Parameterized queries that use PreparedStatement can block most SQL injection attacks.
First: In the case of using parameterized queries, the database system does not treat the contents of the parameters as part of the SQL instruction, but only after the database completes the compilation of the SQL instruction to apply the parameters , so that even if the parameters contain destructive instructions, they will not be run by the database
Second: when composing the SQL string, replace the passed-in argument with a character (replace the single quotation mark character with a contiguous 2 single quote character, because a contiguous 2 single quote character is treated as a single quote character in the character in the SQL database).

strSQL = "SELECT * from users WHERE name = ' + UserName +" '; "
Incoming string:
UserName = "1 ' OR 1=1"

Replace the username with the following characters:
UserName = "1" OR 1=1 "

The last SQL query statement generated is:
strSQL = "SELECT * from users WHERE name = ' 1" OR 1=1 '
The database then goes to the system to look Up records with name "1′ ' OR 1=1", avoiding SQL injection.

Limitations of the

PreparedStatement:
To prevent SQL injection attacks, the PreparedStatement does not allow a placeholder (. has multiple values, and the problem becomes tricky when executing a query with a *in clause *. The following SQL query uses PreparedStatement to return no results:
SELECT * from loan WHERE Loan_type in (?)
Preparedsatement.setstring (1, "' Personal loan ', ' home loan ', ' Gold Loan '");
Workaround:

//to store the variables in inside first into an array string[] in_datas=new string[]{"1", "2", "3"};
StringBuffer buffer = new StringBuffer (); 
for (int i=0;i<in_datas.length-1;i++) {buffer.append ("?,");
} buffer.append ("?"); Use n in the inside phrase. And then for each one.  Assignment PST = conn.preparestatement ("Select Id,name from B where id" ("+buffer.tostring () +"));  
Buffer.tostring () = "?,?,?,?...?" for (int i=0;i<in_datas.length;i++) {Pst.set (I, in_datas[i]);  
   }//Resolve like query String expr = "SELECT * from table where URL like?";  
   pstmt = con.preparestatement (expr);  
   String a= "a";  Pstmt.setstring (1, "%" +a+ "%");//Automatically add single quotes (package parameters) Pstmt.execute (); 

SQL injection:
In SQL injection attacks, malicious users enter through SQL metadata binding, such as: the Login verification SQL query code for a Web site is:
strSQL = "SELECT * from Users WHERE name = ' "+ userName +" ' and pw = ' "+ PassWord +" '; "
maliciously populated:
UserName = "1 ' OR ' 1 ' = ' 1";
PassWord = "1 ' OR ' 1 ' = ' 1";
then the final SQL statement becomes:
strSQL = "SELECT * from users WHERE name = ' 1 ' OR ' 1 ' = ' 1 ' and pw = ' 1 ' or ' 1 ' = ' 1 ';"
because the Where condition is true, this is equivalent to executing:
strSQL = "SELECT * from Users;" The
can therefore be reached without an account password may also log on to the site. If a malicious user is worse, the user fills in:
strSQL = "SELECT * from Users;" The
SQL statement becomes:
strSQL = "SELECT * from users WHERE name = ' Any_value ' and pw ="; DROP table Users
This way, the datasheet is deleted, although there is no login.

several ways to prevent SQL injection:
The first one: Use precompiled statements, through the way of binding variables so that the semantics of SQL statements will not change, avoid using dynamic concatenation of SQL statements to query ', the incoming parameters will only be treated as. Represents a variable to use, so you cannot change the structure of the SQL statement.
Specific implementations include: using stored procedures or implementing parameterized queries using the PreparedStatement implementation.
The second: Never trust user input, on the Web page on the test of incoming data, the use of regular expressions such as filtering special symbols, for verification , but once the new SQL attack, the regular expression library needs to be modified
Third: Do a good job of database account rights Management, for users, as far as possible to give their administrator the right to login access.
Fourth: Strictly encrypt and process the confidential information of the user

Below I implemented a database configuration file to read the connection, you can connect to a different database implementation.

The first step: Configuration file Database.properties, storing the configuration information of various databases

# MySQL Database driver
mysqldriverclass=com.mysql.jdbc.driver
mysqlurl=jdbc:mysql://127.0.0.1/test? Usessl=false
mysqlusername=root
mysqlpassword=wsw011152
# SQL Server 2008 Database driver
Sqlserverdriverclass=net.sourceforge.jtds.jdbc.driver
Sqlserverurl=jdbc:jtds:sqlserver://localhost:1433;d Atabasename=test;
Sqlserverusername=sa
sqlserverpassword=sa
# Oracle  database driver
oracledriverclass= Oracle.jdbc.driver.OracleDriver
Oracleurl=jdbc:oracle:thin: @localhost: 1521:test
Oracleusername=scott
Oraclerpassword=tiger

Step Two: Create a tool class to read the information in this configuration file

Import Java.io.FileInputStream;
Import java.io.FileNotFoundException;
Import java.io.IOException;

Import java.util.Properties;
   public class Propertiesutil {private static Properties prop;
            static{try {prop = new Properties ();
        Prop.load (New FileInputStream ("Database.properties"));
            catch (FileNotFoundException e) {System.out.println ("Load configuration file failed");
        E.printstacktrace ();
        catch (IOException e) {e.printstacktrace ();  Get its driver public static string Getdriverproperties (String key) {return Prop.getproperty (key +) based on the database name
    "Driverclass");
    The URL public static string geturlproperties (String key) {return Prop.getproperty (key + URL) is obtained according to the database name; //Get User name public static string Getusernameproperties (String key) {return Prop.getproperty (key + "user")
    Name "); //Get password public static string getpasswordproperties (String key) {REturn Prop.getproperty (key + "password"); }
}

Step three: Connect to the database

Import Java.io.FileInputStream;
Import java.io.FileNotFoundException;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.OutputStream;
Import java.sql.Connection;
Import Java.sql.DriverManager;
Import Java.sql.ResultSet;
Import java.sql.SQLException;

Import java.util.Properties;

Import com.mysql.jdbc.PreparedStatement;
        public class Jdbcbyproperties {public static void main (string[] args) {//You can connect different databases by simply placing different drivers in the configuration file
            try {//1. Register Driver Class.forName (propertiesutil.getdriverproperties ("MySQL")); 2. Connection database Connection conn = drivermanager.getconnection (Propertiesutil.geturlproperties ("mysq
            L "), Propertiesutil.getusernameproperties (" MySQL "), propertiesutil.getpasswordproperties (" MySQL ")); 3.
            Create executed SQL statement, it is recommended to use preparedstatement String sql = "SELECT * from user where id =?"; PreparedstAtement prep = NULL;
            PREP = (preparedstatement) conn.preparestatement (SQL);
            Prep.setint (1, 1); 4.
            Queries the SQL statement, returns a result set ResultSet results = Prep.executequery (); 5.
                Processes the result set, freeing the resource while (Result.next ()) {System.out.println (Result.getint ("id"));
                System.out.println (result.getstring ("name"));
                System.out.println (Result.getint ("Age"));
            System.out.println (result.getstring ("salary"));
        } conn.close (); catch (ClassNotFoundException e) {//TODO auto-generated catch block System.out.println ("Driver registration failed
            Work ");
        E.printstacktrace ();
        catch (SQLException e) {//TODO auto-generated catch block E.printstacktrace (); }
    }
}

This article refers to blogs:
http://www.importnew.com/5006.html

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.