JDBC笔记

/**
 * JDBC连接Mysql演示
 * @author ZHQL
 */
``public class Test01 {

	public static void main(String[] args) {
		ResultSet rs = null;
		try {
			rs = DBUitl.query("select * from t_user t");
			//循环结果集
			while(rs.next()){
/*				System.out.println(rs.getLong("id") + " " 
			                     + rs.getString("name") +" " 
						         + rs.getDate("birthday"));*/
				System.out.println(rs.getLong(1) + " " 
			                     + rs.getString(2) +" " 
						         + rs.getDate(4));
			}			
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			//后打开要先关闭
			DBUitl.close(rs);
		}
	}

}

/**
 * JDBC执行增删改演示
 * @author ZHQL
 */
public class Test02 {

	public static void main(String[] args) {
		String url ="jdbc:mysql://localhost:3306/db1726";
		Connection conn = null;
		Statement sm = null;
		try {
			//加载驱动
			Class.forName("com.mysql.jdbc.Driver");
			//创建数据库连接
			conn = DriverManager.getConnection(url,"u1726","u1726");
			conn.setAutoCommit(false);//把事务提交改为手动
			//创建语句
			sm = conn.createStatement();
			//String sql = "INSERT INTO t_class(NAME,CHARGER,CREATE_DATE)VALUES ('测试班级','李凤',NOW())";
			String sql1 = "update t_class set name = '班级名称1' where id = 11";
			String sql2 = "delete from t_class where id = 11";
			//执行查询语句(这两个语句就是一个事务)
			int i = sm.executeUpdate(sql1);
			Savepoint sp1 = conn.setSavepoint();
			i = sm.executeUpdate(sql2);
			conn.rollback(sp1);//回滚到一个保存点
			conn.commit();//提交事务
			System.out.println("更新的行数:" + i);
		} catch (Exception e) {
			try {
				conn.rollback();//回滚事务
			} catch (SQLException e1) {
				e1.printStackTrace();
			}//回滚
			e.printStackTrace();
		}finally{
			//后打开要先关闭
			try {
				sm.close();
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		

	}

}
上一篇:学好一宁喜欢的 Arthas SM 命令, 做好葱油饼


下一篇:CUDA是什么-CUDA简介