1.下载mysql的jdbc驱动包。

  http://dev.mysql.com/downloads/connector/

2.获取连接。

  

public static Connection GetConnection() {
        Connection conn = null;

        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/jsp_db", "root", "root");
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        } finally {

        }

        return conn;
    }

 

3.增删改查。

public static void InsertUserData(Connection conn) throws SQLException {

        String sql = "insert into tbl_user(id,name,password,email)" 
        + "values(10, 'Tom', '123456', 'tom@gmail.com')";

        Statement st = conn.createStatement();
        int count = st.executeUpdate(sql);
        System.out.println("向用户表中插入了" + count + "");

    }

 

4.事务。

try {

            conn = GetConnection();
            conn.setAutoCommit(false);
            InsertUserData(conn);
            InsertAddressData(conn);

            conn.commit();

        } catch (SQLException e) {
            // TODO Auto-generated catch block

            System.out.println("=========捕获到SQL异常=====");
            e.printStackTrace();

            try {
                conn.rollback();
                System.out.println("===事务回滚成功====");
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        } finally {
            try {
                if (conn != null) {
                    conn.close();
                }
            } catch (Exception e3) {
                e3.printStackTrace();
            }
        }

5.源码

  https://git.oschina.net/zkzk945/JavaEE.git