JDBC(原始不考虑事务)
package cn.gts.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.junit.Test;
import cn.gts.entity.User;
public class Jdbc {
@Test
public void jdbcTest() {
Connection conn = null;
PreparedStatement psmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/test";
String username = "root";
String password = "123";
conn = DriverManager.getConnection(url,username,password);
String sql = "select * from user where username = ?";
psmt = conn.prepareStatement(sql);
psmt.setString(1, "zhangSan");
rs = psmt.executeQuery();
while(rs.next()) {
String username = rs.getString("username");
String password = rs.getString("password");
User user = new User();
user.setUsername(username);
user.setPassword(password);
System.out.println(user);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
rs.close();
psmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
JDBC演示转账(事务案例)
public void transfer(boolean b) {
Connection con = null;
PreparedStatement pstmt = null;
try {
con = JdbcUtils.getConnection();
con.setAutoCommit(false);
String sql = "update account set balance=balance+? where id=?";
pstmt = con.prepareStatement(sql);
pstmt.setDouble(1, -10000);
pstmt.setInt(2, 1);
pstmt.executeUpdate();
if(b) {
throw new Exception();
}
pstmt.setDouble(1, 10000);
pstmt.setInt(2, 2);
pstmt.executeUpdate();
con.commit();
} catch(Exception e) {
if(con != null) {
try {
con.rollback();
} catch(SQLException ex) {}
}
throw new RuntimeException(e);
} finally {
JdbcUtils.close(con, pstmt);
}
}