first, connectivity issues
The previous just introduced how to connect the database, also wrote the corresponding template, but its maintainability is very poor, then how to solve this problem?
First write a configuration file jdbc.properties
<span style= "FONT-SIZE:18PX;" >## mysqldriver=com.mysql.jdbc.driverurl=jdbc:mysql://localhost:3306/hncu?useunicode=true& characterencoding=utf-8username=rootpassword=1234## Oracle#driver=oracle.jdbc.driver.oracledriver#url=jdbc:o Racle:thin:@192.168.31.12:1521:orcl#username=scott#password=tiger</span>
Then create a factory that generates the connection connfactory. Java
<span Style= "FONT-SIZE:18PX;" >package cn.hncu.hibernate0;import java.io.ioexception;import Java.sql.connection;import Java.sql.DriverManager Import Java.util.properties;public class Connfactory {private static Connection conn;static {try {//Read config file Properties p = New Properties ();p. Load (ConnFactory.class.getClassLoader (). getResourceAsStream ("jdbc.properties")); String Driver = p.getproperty ("Driver"); String url = p.getproperty ("url"); String username = p.getproperty ("username"); String pwd = p.getproperty ("password"); Class.forName (driver); conn = Drivermanager.getconnection (URL,USERNAME,PWD); System.out.println ("Connected to Database ..." +conn); catch (Exception e) {throw new RuntimeException ("Failed to read config file", e);}} public static Connection Getconn () {return conn;} public static void Main (string[] args) {getconn ();}} </span>
Finally obtained directly through Connfactory.getconn (). The benefit of this is that when you change the type of database you want to connect to, you only need to modify the contents of the configuration file.
second, explain the GetXXX () method
<span style= "FONT-SIZE:18PX;" ><span style= "White-space:pre" ></span> @Testpublic void Getxxxdemo () throws Exception{statement st = Connfactory.getconn (). createstatement (); String sql = "SELECT * from book"; ResultSet rs = st.executequery (sql), while (Rs.next ()) {Integer id = rs.getint (1);//1 here represents the first column in the data table, and the following is the same as String name = Rs.getstring (2);//double price = (Double) rs.getobject (3), or//exception, because the internal is the use of BigDecimal to handle Double Price = Rs.getdouble (3); O bject datetime = Rs.getobject (4);//Read the date and time as a whole System.out.println (id+ "," +name+ "," +price+ "," +datetime "); String strdatetime = DateTime.ToString (); System.out.println (strdatetime); strdatetime = Rs.getdate (4) + "--" +rs.gettime (4);//date and time can be obtained separately System.out.println (" ::: "+strdatetime);} Connfactory.getconn (). Close ();} </span>
Note: For the autogrow column, after deleting and inserting a new record, the sequence number will not go back and continue to grow. That is, the middle will appear empty
Iii. explaining the three executexxx () methods in statement
1. ExecuteQuery: Only SELECT statements can be executed
2. Executeupdate: Insert, delete, and UPDATE statements can be executed, but cannot execute select
3, execute: Adding and deleting 4 kinds of (arbitrary) statements can be executed. This method returns false when executing a non-select statement, returns True when the SELECT statement is executed, and the St object caches the results of that query, and I
The result set can be obtained by resultset rs = St.getresultset ()
<span style= "FONT-SIZE:18PX;" ><span style= "White-space:pre" ></span> @Testpublic void Executexxxdemo () throws Exception{statement St = Connfactory.getconn (). createstatement (); String sql = "SELECT * from book";//string sql = "Insert to book (name,price,pub) VALUES (' Software engineering ', 22.35, ' 2015-12-05 22:12:2 3 ') ";//string sql =" Update book set price=38.88 where name= ' software engineering ' ";//string sql =" Delete from book where name= ' Software engineering ' ";
//st.executequery (SQL);//st.executeupdate (SQL); Boolean boo = St.execute (sql); if (boo) {ResultSet rs = St.getresultset (); while (Rs.next ()) {System.out.println (Rs.getobject (2));}} </span>
Iv. Anti-black technology in database query (preprocessing statement)
case, user login (splicing SQL statements with user input information----dangerous)
<span style= "FONT-SIZE:18PX;" ><span style= "White-space:pre" ></span> @Test//user login public void login () throws exception{ Connection con = connfactory.getconn (); Statement st = Con.createstatement (); Scanner sc = new Scanner (system.in); int id = Sc.nextint (); Sc.nextline (); String name = Sc.nextline (); String sql = "SELECT COUNT (*) from stud where id=" +id+ "and Sname= '" +name+ "'"; SYSTEM.OUT.PRINTLN ("sql:" +sql); ResultSet rs = st.executequery (sql), Rs.next (), int a = Rs.getint (1), if (a<=0) {System.out.println ("login unsuccessful");} ELSE{SYSTEM.OUT.PRINTLN ("Login Successful");} Con.close (); } </span>
Black method, Input: 1002 (Enter) 1 ' or ' 1 ' = ' 1
Therefore: If you need to use the user input information to splice SQL statements, you can not use statement, otherwise the user may build a WHERE clause in a true condition to break through the protection for the above situation
PreparedStatement should be used to solve the situation!
<span style= "FONT-SIZE:18PX;" ><span style= "White-space:pre" ></span> @Test//user login Black: 1002 (enter) 1 ' or ' 1 ' = ' 1public void login2 ( ) throws Exception{scanner sc = new Scanner (system.in); Connection con = connfactory.getconn (); String sql = "SELECT COUNT (*) from stud where id=? and sname=? "; /where user input is required, use placeholder ('? ') PreparedStatement PST = con.preparestatement (SQL) by assigning a parameter to the placeholder, and/or setting the argument int id = sc.nextint (); Sc.nextline ();p st.setint (1, id); The parameter 1----represents the 1th placeholder string name = Sc.nextline ();p st.setstring (2, name);//parameter 2ResultSet rs = Pst.executequery (); Rs.next (); int a = Rs.getint (1), if (a<=0) {System.out.println ("login unsuccessful");} ELSE{SYSTEM.OUT.PRINTLN ("Login Successful");} Con.close (); } </span>
v. Get an auto-grow column (such as ID)
<span style= "FONT-SIZE:18PX;" ><span style= "White-space:pre" ></span> @Test//Demo get autogrow column such as Idpublic Void Saveauto () throws exception{ Connection con = connfactory.getconn (); String sql = "INSERT into book (name,price,pub) VALUES (' Java EE ', 100.8, ' 2013-06-12 08:30:30 ')"; Statement st = Con.createstatement ();//st.executeupdate (SQL); St.executeupdate (Sql,statement.return_generated_keys ); ResultSet rs = St.getgeneratedkeys ();//inside encapsulates all automatically generated values if (Rs.next ()) {int id = rs.getint (1);// Get 1th autogrow column System.out.println ("Auto-growing ID:" +id);} System.out.println ("-----------------");//preprocessing statement sql = "INSERT into book (Name,price) VALUES (?,?)"; PreparedStatement PST = con.preparestatement (Sql,statement.return_generated_keys);p st.setstring (1, "Computer based"); Pst.setdouble (2);p st.executeupdate (); ResultSet rs2 = Pst.getgeneratedkeys ();//inside encapsulates all automatically generated values if (Rs2.next ()) {int id = rs2.getint (1);// Get 1th autogrow column System.out.println ("Auto-growing ID:" +id);}} </span>
VI. Presentation Batch statements
public void Batch () throws exception{connection con = Connfactory.getconn (); String sql = "INSERT into book (name,price,pub) VALUES (' Java EE ', 100.8, ' 2015-06-12 08:30:30 ')"; Statement st = Con.createstatement (); for (int i=0;i<10;i++) {st.addbatch (SQL);} sql = "Update book set price=price*1.1 where price>100"; St.addbatch (SQL), int[] A = St.executebatch (); for (int r:a) {Syst Em.out.println (R);//r the number of records affected by each SQL statement}}
Pretreatment
public void Preparedbatch () throws exception{connection con = Connfactory.getconn (); String sql = "INSERT into book (name,price,pub) VALUES (?,?,?)"; PreparedStatement PST = con.preparestatement (SQL), for (int i=0;i<5;i++) {pst.setstring (1, "Java" +i);p st.setdouble ( 2, 55.85+i);p st.setstring (3, "2016-12-10 07:07:08");p St.addbatch (); PST cannot be taken with parameter Sql}//pst.executebatch (); int[] A = Pst.executebatch (); for (int r:a) {System.out.println (R);// R is the number of records affected by each SQL statement}}
Note: preprocessingthe way can not take parameter SQL, ordinary need
What "Java" does to database operations (including preprocessing in the database)