JDBC Operations Database __ Database

Source: Internet
Author: User
Package com.lxz;
Import java.sql.Connection;
Import Java.sql.DriverManager;
Import java.sql.PreparedStatement;
Import Java.sql.ResultSet;

Import java.sql.SQLException; 
		public class StringAndDate2 {//Create a method to connect a database with JDBC public ResultSet getresultset (String sql) {Connection conn = null;
		PreparedStatement PS = null;
		ResultSet rs = null;
		String url = "Jdbc:mysql://localhost:3306/test?useunicode=true&characterencoding=utf-8";
		String user = "root";
		String password = "123456";
			try {//1. Load Driver class Class.forName ("Com.mysql.jdbc.Driver");
			or new Com.mysql.jdbc.Driver ();
			2. Create Connection conn = drivermanager.getconnection (URL, user, password); 3. To create the PreparedStatement object//To execute the SQL statement, you must obtain a java.sql.Statement instance, and the statement instance is divided into the following three kinds//(1) to execute the static SQL statement.
			Typically implemented through Statement instances//Statement stmt = Conn.createstatement (); (2) Execute dynamic SQL statements.
			Typically implemented through PreparedStatement instances//PreparedStatement PS = conn.preparestatement (SQL); (3) Execute the database stored procedure. Typically implemented via CallableStatement instance//CallAblestatement cs = Conn.preparecall ("{Call DEMOSP (?,?)}");
			PS = conn.preparestatement (SQL); 4. Executing the SQL statement//Statement interface provides three methods of executing SQL statements, Executequery,executeupdate,execute//(1) ResultSet executequery (String s
			qlstring): Executes the SQL statement that queries the database, returns a//ResultSet object//ResultSet rs = ps.executequery ("SELECT * from ...");
			(2) int executeupdate (String//SqlString): Used to execute INSERT/UPDATE/DELETE statements and//SQL DDL statements such as CREATE table and drop table
			int rows = Ps.executeupdate ("INSERT into ...");
			(3) Execute (sqlstring): Used to execute statements//Boolean flag = Ps.execute (String sql) that returns multiple result sets, multiple updates, or combinations of both;
			rs = Ps.executequery ();  5. Processing results//(1) Performing the update operation returns the number of records affected by this operation//(2) The result returned by the execution query is a ResultSet object//resultset contains all the rows of the conditions in the SQL statement, accessed through get
			while (Rs.next ()) {//String name = rs.getstring (' name '); String pwd = rs.getstring (1);
			More efficient, from right to left to numbered, starting at 1/} catch (ClassNotFoundException e) {System.out.println ("No driver class found");
		E.printstacktrace (); catch (SQLExceptione) {e.printstacktrace ();
				finally {//5. Close the JDBC Object if (rs!= null) {try {rs.close ();
				catch (SQLException e) {e.printstacktrace ();
				} if (ps!= null) {try {ps.close ();
				catch (SQLException e) {e.printstacktrace ();
				} if (conn!= null) {try {conn.close ();
				catch (SQLException e) {e.printstacktrace ();
	}} return RS;
	The difference between//PreparedStatement and statement. 1. Readability and maintainability of code//stmt.executeupdate (INSERT into tb_test (COL1,COL2,COL3) VALUES (' +var1+ "', ' +var2+ ', '" +var3+ ')
	");
	PreparedStatement//PS = Conn.preparestatement ("INSERT into tb_test (COL1,COL2,COL3) VALUES (?,?,?)");
	Ps.setstring (1,VAR1);
	Ps.setstring (2,VAR2);
	Ps.setstring (3,VAR3); 2.PreparedStatement Maximum performance//* Each database will do its best to provide maximum performance optimizations for precompiled statements, because precompiled statements can be called repeatedly, so when the statement is compiled by the database compiler, the execution code is cached. So the next call, as long as the same precompiled statement does not need to be compiled, as long as the parameters passed directly into the compiled statement execution code (equivalent to a function) will be executed, this is not to say that only a connection of multiple executions of the precompiled statements are cached, but the entire database, As long as the precompiled languageSyntax and caching are matched, and can be executed directly at any time without having to compile again. In a statement statement, even the same operation, and because the data for each operation is different, so the opportunity to match the entire statement is very small, almost impossible to match, for example: INSERT INTO Tb_test (col1,col2) VALUES (' 11 ', '
	22 ');
	Insert into Tb_test (col1,col2) VALUES (' 11 ', ' 23 ');
	Even if the same operation but because the data content is not the same, so the whole statement itself can not match, do not have the meaning of cached statements. The fact is that no database is cached for the compiled code of the normal statement. This will compile the incoming statement once for each execution.  Of course not, so precompiled statements are bound to be cached, the database itself uses a strategy, such as frequency, to determine when the existing precompiled results will no longer be cached. To save more space to store the new precompiled statement.//3. Improve security//String sql = Select
	* FROM Tb_test where username= ' "+username+" ' and password= ' "+password+" "; If the (' or ' 1 ' = ' 1 ') is passed in, you'll find all the information//even pass (';d ROP table tb_test where ' 1 ' = ' 1 '), and just some of the databases will execute//If you use precompiled statements, any incoming content will not be the same as the original language Any matching relationship between the sentences.
	(provided that the database itself supports precompilation)//Another: execution efficiency: Statement take the way of directly compiling the SQL statement, throw it to the database to execute, while PreparedStatement compiles the SQL statement first, then fills the parameter, so the efficiency will be higher.
	The JDK documentation says that the SQL statement is precompiled and stored in the PreparedStatement object, and can then be used efficiently to execute the statement multiple times. 
Statement because of the possible need to take string and variable stitching, it is easy to do SQL injection attacks, and preparedstatement because of the pre//compile, and then fill the parameters, there is no SQL injection problem.
 }

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.