【java】對資料庫操作的那些事(包含資料庫中的預先處理)

來源:互聯網
上載者:User

標籤:bool   方式   cut   main   軟體   resource   案例   localhost   for   

一、串連問題

前面剛介紹了怎麼串連資料庫,也寫了對應的模板。可是它的可維護性很差。那麼怎麼解決問題呢?

首先寫一個設定檔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:oracle:thin:@192.168.31.12:1521:orcl#username=scott#password=tiger</span>


然後建立一個產生串連的工廠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 {//讀取設定檔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("已串連到資料庫..."+conn);} catch (Exception e) {throw new RuntimeException("讀取設定檔失敗", e);}}public static Connection getConn(){return conn;}public static void main(String[] args) {getConn();}}</span>
最後直接通過ConnFactory.getConn()獲得。

這要做的優點,當改變所要串連的資料庫類型時,僅僅須要改動設定檔裡的內容就可以。


二、解說getXXX()方法

<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表示資料表中的第一列,以下同理String name = rs.getString(2);//Double price = (Double)rs.getObject(3);//出異常,由於內部是採用BigDecimal來處理Double price = rs.getDouble(3);Object dateTime = rs.getObject(4);//把日期和時間作為一個總體讀取出來System.out.println(id+","+name+","+price+","+dateTime);String strDateTime = dateTime.toString();System.out.println(strDateTime);strDateTime = rs.getDate(4)+"--"+rs.getTime(4);//日期和時間能夠單獨擷取System.out.println(":::"+strDateTime);}ConnFactory.getConn().close();}</span>
註:對於自己主動增長列。刪除之後再插入新記錄,序號不會回頭,繼續往前增長。即中間會出現空號


三、解說Statement中的三個executeXXX()方法

1、executeQuery: 僅僅能運行select語句

2、executeUpdate: 能夠運行insert、delete和update語句,但不能運行select

3、execute:增刪改查的4種(隨意)語句都能運行。該方法若運行非select語句時返回false,運行select語句時返回true,且st對象會緩衝該次查詢的結果。我

們可通過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 into book(name,price,pub) values('軟體project',22.35,'2015-12-05 22:12:23')";//String sql = "update book set price=38.88 where name='軟體project'";//String sql = "delete from book where name='軟體project'";    //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>


四、資料庫查詢時防黑技術(預先處理語句)

案例、使用者登入(通過使用者輸入資訊來拼接sql語句----非常危急)

<span style="font-size:18px;"><span style="white-space:pre"></span>@Test//使用者登入    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("登入不成功");}else{System.out.println("登入成功");}con.close();   }</span>
黑的方法。輸入:1002(斷行符號)   1‘ or ‘1‘=‘1
因此:假設須要用 使用者輸入的資訊 來拼接 sql語句,就不能用statement。否則使用者能夠通過構建where子句中的一個true條件來突破防護對於上面的情

況,應該用PreparedStatement來解決!

<span style="font-size:18px;"><span style="white-space:pre"></span>@Test//使用者登入     黑:1002(斷行符號)   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=?";//須要使用者輸入的地方,用預留位置('?')來取代。然後在興許通過設參來給預留位置賦值PreparedStatement pst = con.prepareStatement(sql);//設定參數int id = sc.nextInt(); sc.nextLine();pst.setInt(1, id); //參數1----代表第1個預留位置String name = sc.nextLine();pst.setString(2, name);//參數2ResultSet rs = pst.executeQuery();rs.next();int a = rs.getInt(1);if(a<=0){System.out.println("登入不成功");}else{System.out.println("登入成功");}con.close();   }</span>


五、擷取自己主動增長列(如id)
<span style="font-size:18px;"><span style="white-space:pre"></span>@Test //示範擷取自己主動增長列如idpublic void saveAuto() throws Exception{Connection con = ConnFactory.getConn();String sql = "insert into book(name,price,pub) values('JavaEE',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();//裡面封裝了自己主動產生的全部值if(rs.next()){int id = rs.getInt(1);//擷取第1個自己主動增長列System.out.println("自己主動增長的id:"+id);}System.out.println("-----------------");//預先處理語句sql =  "insert into book(name,price) values(?,?)";PreparedStatement pst = con.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);pst.setString(1, "電腦基礎");pst.setDouble(2, 28);pst.executeUpdate();ResultSet rs2 = pst.getGeneratedKeys();//裡面封裝了自己主動產生的全部值if(rs2.next()){int id = rs2.getInt(1);//擷取第1個自己主動增長列System.out.println("自己主動增長的id:"+id);}}</span>


六、示範批處理語句

public void batch() throws Exception{Connection con = ConnFactory.getConn();String sql = "insert into book(name,price,pub) values('JavaEE',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){System.out.println(r);//r為每條sql語句所影響的記錄數}}

預先處理

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);pst.setDouble(2, 55.85+i);pst.setString(3, "2016-12-10 07:07:08");pst.addBatch(); //pst的方式不能帶參數sql}//pst.executeBatch();int[] a = pst.executeBatch();for(int r:a){System.out.println(r);//r為每條sql語句所影響的記錄數}}

注意:預先處理的方式不能帶參數sql,普通的須要



















【java】對資料庫操作的那些事(包含資料庫中的預先處理)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.