標籤:java web
接上節:
對上節http://4440271.blog.51cto.com/4430271/1661684
程式修改:
package com.jike.jdbc;import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;import java.sql.Statement;public class TransactionTest {public static Connection getConnection() {Connection conn = null;try {Class.forName("com.mysql.jdbc.Driver");conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/info", "*****", "******");} catch (Exception e) {// TODO: handle exceptione.printStackTrace();}return conn;}// 向使用者表中插入資料// 對代碼修改public static void insertUserData(Connection conn) throws SQLException {// ctrl+shift+f格式化代碼String sql = "insert into tbl_user(id, name, password, email)"+ "values(10, ‘Tom‘, ‘2525252‘, ‘[email protected]‘)";Statement st = conn.createStatement();int count = st.executeUpdate(sql);System.out.println("向使用者表中插入了" + count + "條資料");// conn.close();}// 向地址表中插入資料public static void insertAddressData(Connection conn) throws SQLException {String sql = "insert into tbl_address(id, city, country, user_id)"+ "values(1, ‘shanghai‘, ‘china‘, ‘10‘)";Statement st = conn.createStatement();int count = st.executeUpdate(sql);System.out.println("向地址表中輸入了" + count + "條記錄");// conn.close();}public static void main(String[] args) {Connection conn = null;try {conn = getConnection();conn.setAutoCommit(false); // 禁止事務自動認可insertUserData(conn);insertAddressData(conn);// 這裡,在提交insertAddressData方法是拋出異常,異常被捕獲,因此交易回復。//提交事務conn.commit();} catch (Exception e) {System.out.println("*************捕獲到sq異常************");e.printStackTrace();try {conn.rollback(); //如果提交失敗則復原System.out.println("交易回復成功");} catch (Exception e2) {// TODO: handle exceptione2.printStackTrace();}}finally{try {if(conn != null){conn.close();}} catch (Exception e3) {// TODO: handle exceptione3.printStackTrace();}}}}
輸出結果:
650) this.width=650;" src="http://s3.51cto.com/wyfs02/M01/6E/6E/wKioL1V8dG3j-FrNAAPgFJyMhHQ266.jpg" title="QQ20150614021257.jpg" alt="wKioL1V8dG3j-FrNAAPgFJyMhHQ266.jpg" />
在資料庫中:
650) this.width=650;" src="http://s3.51cto.com/wyfs02/M01/6E/71/wKiom1V8cv3DuuSAAAD8jBiZGdQ758.jpg" title="QQ20150614021402.jpg" alt="wKiom1V8cv3DuuSAAAD8jBiZGdQ758.jpg" />
資料沒有插入,說明復原成功,資料的一致性沒有受到破壞。
JDBC 編程最佳化:
將配置資訊提取出來,放到屬性檔案裡面:
建立屬性檔案 : 在src目錄下右鍵,點擊 new--> other --> General-->File-->next---> 檔案名稱. properties-->finish
點擊add,添加如下內容:
650) this.width=650;" src="http://s3.51cto.com/wyfs02/M00/6E/6E/wKioL1V85AKxicIvAAEPnDc4aCE796.jpg" title="QQ20150614100839.jpg" alt="wKioL1V85AKxicIvAAEPnDc4aCE796.jpg" />
點擊下方的source可以看到:
650) this.width=650;" src="http://s3.51cto.com/wyfs02/M00/6E/72/wKiom1V84rXCTZspAACkbpeJf3c725.jpg" title="QQ20150614101036.jpg" alt="wKiom1V84rXCTZspAACkbpeJf3c725.jpg" />
建立如下兩個類:
650) this.width=650;" src="http://s3.51cto.com/wyfs02/M01/6E/6E/wKioL1V85Nzh6lFKAABoDc97saM116.jpg" title="QQ20150614101210.jpg" alt="wKioL1V85Nzh6lFKAABoDc97saM116.jpg" />
在工廠類中添加代碼:
package com.jike.jdbc.util;import java.io.InputStream;import java.sql.Connection;import java.sql.DriverManager;import java.util.Properties;// 建立資料庫連接工廠類,放在util包下public class ConnectionFactory {// 建立四個成員變數用於儲存從屬性檔案中讀出的資料庫配置資訊private static String driver;private static String dburl;private static String user;private static String password;private static final ConnectionFactory factory = new ConnectionFactory();//定義Connection類型變數保持資料連線private Connection conn;// 配置資訊的讀取static{//靜態代碼塊用於初始化類,為類的屬性賦值,靜態代碼塊只執行一次Properties prop = new Properties();//定義屬性類,用於儲存屬性檔案中的索引值對try {InputStream in = ConnectionFactory.class.getClassLoader().getResourceAsStream("dbcofig.properties");// 擷取屬性檔案中的內容// 首先獲得當前類的類載入器,然後通過載入器中的getResourceAsStream方法讀取屬性檔案中的內容。// 這個方法將屬性檔案中的內容讀取到一個輸入資料流中prop.load(in);//從輸入資料流中讀取屬性列表,即屬性檔案中的索引值對列表} catch (Exception e) {// TODO: handle exceptionSystem.out.println("讀取設定檔錯誤");}//將讀取到的值賦值給成員變數driver = prop.getProperty("driver");dburl = prop.getProperty("dburl");user = prop.getProperty("user");password = prop.getProperty("password");}// 定義預設的建構函式private ConnectionFactory(){}// 用於擷取ConnectionFactory執行個體public static ConnectionFactory getInstance(){return factory;}// 擷取資料庫連接的方法public Connection makeConnection(){try {Class.forName(driver);conn = DriverManager.getConnection(dburl, user, password);} catch (Exception e) {// TODO: handle exceptione.printStackTrace();}return conn;}}
在測試類別中添加如下代碼:
package com.jike.test;import java.sql.Connection;import com.jike.jdbc.util.ConnectionFactory;public class ConnectionFactoryTest {/** * @param args */public static void main(String[] args) throws Exception{// TODO Auto-generated method stubConnectionFactory cf = ConnectionFactory.getInstance();Connection conn = cf.makeConnection();System.out.println(conn.getAutoCommit());}}
測試結果為:true
然後建立相應的DTO
650) this.width=650;" src="http://s3.51cto.com/wyfs02/M00/6E/72/wKiom1V86XXy9K0qAAA4NwvXzuI726.jpg" title="QQ20150614103911.jpg" alt="wKiom1V86XXy9K0qAAA4NwvXzuI726.jpg" />
添加相應的實體類:
在IdEntity類中:
package com.jike.entity;// 封裝主鍵資訊public abstract class IdEntity {protected Long id;public Long getId() {return id;}public void setId(Long id) {this.id = id;}}
在User類中:
package com.jike.entity;// 建立使用者資訊的實體類public class User extends IdEntity {// 新增成員屬性,與資料庫中user表的屬性一一對應private String name;private String password;private String email;public String getName() {return name;}public void setName(String name) {this.name = name;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public String getEmail() {return email;}public void setEmail(String email) {this.email = email;}@Overridepublic String toString() {return "User [name=" + name + ", password=" + password + ", email="+ email + ", id=" + id + "]";}}
在Address類中:
package com.jike.entity;public class Address extends IdEntity {private String city;private String country;private Long userId;public String getCity() {return city;}public void setCity(String city) {this.city = city;}public String getCountry() {return country;}public void setCountry(String country) {this.country = country;}public Long getUserId() {return userId;}public void setUserId(Long userId) {this.userId = userId;}@Overridepublic String toString() {return "Address [city=" + city + ", country=" + country + ", userId="+ userId + ", id=" + id + "]";}}
這樣,就完成了實體類的建立。
建立DAO
650) this.width=650;" src="http://s3.51cto.com/wyfs02/M00/6E/73/wKiom1V9BC6wkTLJAABSFDLcZSg309.jpg" title="QQ20150614123319.jpg" alt="wKiom1V9BC6wkTLJAABSFDLcZSg309.jpg" />
在介面UserDao中添加:
package com.jike.dao;import java.sql.Connection;import java.sql.SQLException;import com.jike.entity.User;//定義實作類別的行為public interface UserDao {//定義對資料庫的操作public void save(Connection conn, User user) throws SQLException;public void update(Connection conn, Long id, User user) throws SQLException;public void delete(Connection conn, User user) throws SQLException;}
在介面的實作類別UserDaoImpl中添加
package com.jike.dao.impl;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.SQLException;import com.jike.dao.UserDao;import com.jike.entity.User;public class UserDaoImpl implements UserDao {/* * 儲存使用者資訊 */@Overridepublic void save(Connection conn, User user) throws SQLException {// TODO Auto-generated method stub//PreparedStatement是jdbc用於執行sql查詢語句的api之一,用來執行參數化的查詢//?是預留位置PreparedStatement ps = conn.prepareStatement("insert into tbl_user(name, password, email) values (?,?,?)");//參數設定ps.setString(1, user.getName());//索引從1開始ps.setString(2, user.getPassword());ps.setString(3, user.getEmail());ps.execute();//將參數傳入的user對象中的相關資訊儲存到資料庫表中}/* * 根據使用者id更新使用者資訊 */@Overridepublic void update(Connection conn, Long id, User user) throws SQLException {// TODO Auto-generated method stubString updateSql = "update tbl_user set name=?, password=?, email=? where id=?";PreparedStatement ps = conn.prepareStatement(updateSql);ps.setString(1, user.getName());ps.setString(2, user.getPassword());ps.setString(3, user.getEmail());ps.setLong(4, id);ps.execute();}/* * 刪除指定的使用者資訊 */@Overridepublic void delete(Connection conn, User user) throws SQLException {// TODO Auto-generated method stubPreparedStatement ps = conn.prepareStatement("delete from tbl_user where id=?");ps.setLong(1, user.getId());ps.execute();}}
添加測試程式:
package com.jike.test;import java.sql.Connection;import com.jike.dao.UserDao;import com.jike.dao.impl.UserDaoImpl;import com.jike.entity.User;import com.jike.jdbc.util.ConnectionFactory;public class UserDaoTest {/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubConnection conn = null;try {conn = ConnectionFactory.getInstance().makeConnection();conn.setAutoCommit(false);System.out.println(conn.getAutoCommit());UserDao userDao = new UserDaoImpl();User tom = new User();tom.setName("Tom");tom.setPassword("123");tom.setEmail("[email protected]");userDao.save(conn, tom);conn.commit(); //提交事務} catch (Exception e) {// TODO: handle exceptiontry {conn.rollback();} catch (Exception e2) {// TODO: handle exceptione2.printStackTrace();}}}}
查看資料庫,新加入的資料成功提交。
極客學院:http://www.jikexueyuan.com/course/566_6.html?ss=2
JSP(3) ----JDBC編程2