Monthly Archives: 三月 2016

InnoDB

SHOW TABLE STATUS

Name Engine Version
tbl_user InnoDB 10
tbl_address InnoDB 10

ALTER TABLE jsp_db.`tbl_address` ENGINE = INNODB;

ALTER TABLE jsp_db.`tbl_user` ENGINE = INNODB;

InnoDB 配置

http://dev.mysql.com/doc/refman/5.0/en/innodb-configuration.html

 

java代码段:

package com.aries4u.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * Created by Liukaibo on 2016/3/16.
 */
public class TransactionTest {
    public static Connection getConnection() {
        Connection conn = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/jsp_db", "root", "mysqlroot");
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return  conn;
    }

    public static void insertUserData(Connection conn) throws SQLException {
        String sql = "INSERT INTO tbl_user(id, name, password, email)" +
                "VALUES(10, 'TOM', '123456', 'tom@126.com')";
        Statement st = null;
        int count = 0;
        st = conn.createStatement();
        count = st.executeUpdate(sql);
        System.out.println("向用户表插入了" + count + "条记录");
    }

    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 = null;
        int count = 0;
        st = conn.createStatement();
        count = st.executeUpdate(sql);
        System.out.println("向地址表插入了" + count + "条记录");
    }

    public static void main(String[] args) throws SQLException {
        Connection conn = null;
        try {
            conn = getConnection();
            conn.setAutoCommit(false);  // 只有设置成false的时候InnoDB才有效

            insertUserData(conn);
            insertAddressData(conn);

            conn.commit();
        } catch (SQLException e) {
            System.out.println("===========捕获到SQL异常===============");
            e.printStackTrace();
            if (conn != null) {
                conn.rollback();
                System.out.println("===========事务回滚成功===============");
            }
        } finally {
            if (conn != null) {
                conn.close();
            }
        }
    }
}