SQL基础

1、SQL语句基础

1、DQL(Data Query Language) :查询,由select关键字完成
2、DML(Data Manipulation Language):操作,由insert、update、delete三个关键字完成
3、DDL(Data Definition Language):定义,由create、alter、drop、truncate四个关键字完成
4、DCL(Data Control Language):控制,由grant、revoke两个关键字完成
5、TCL(Transaction Control Language):事务控制。由commit、rollback、savepoint三个关键字完成

2、SQL语法

select 字段 from 表名 where… group by … having … order by …
原则:能在where中过滤的数据,尽量在where中过滤,效率较高。having的过滤是专门对分组之后的数据进行过滤的。

3、Statement 和 PreparedStatement

1、Statement存在SQL注入问题
2、Statement是编译一次执行一次,PreparedStatement编译一次可执行N次。PreparedStatement效率较高一些。
3、PreparedStatement会在编译阶段做类型的安全检查

4、需要SQL注入时,只能用Statement,如价格的从高到低、从低到高的排序。

4、JDBC事务机制

try{
    conn = DriverManager.getConnection(url,user,password);
    conn.setAutoCommit(false);//开启事务
    sql...
    conn.commit();//手动提交
}catch(Exception e){
   //回滚事务
    if(conn!=null){
       conn.rollback();
    }
}

5、JDBC封装类

public class JdbcUtil{

	//static使得变量不需要通过创建对象来调用,可以直接用类来访问
	private static String driver = null;
	private static String url = null;
	private static String user = null;
	private static String password = null;

	Connection conn = null;
	PreparedStatement ps = null;
	ResultSet rs = null;
	
1、读取数据库配置文件
	public static void init(){
		ResourceBundle bundle = ResourceBundle.getBundle("jdbc");
		driver = bundle.getString("driver");
		url= bundle.getString("url");
		user = bundle.getString("user");
		password = bundle.getString("password");
	}
	
2、注册驱动
	//类加载
	static{
		//体现static可以直接通过类来调用的好处
		init();
		try{
			//反射机制
			Class.forName(driver);
		}catch(ClassNotFoundException e){
			e.printStackTrace();
		}
	}
	
3、连接数据库
	public static Connection getConnection() throws SQLException{
		return DriverManager.getConnection(url,user,password);
	}
	
4、获取预编译数据库操作对象
	//外部通过对象调用时,会自动调用getConnection()
	public PreparedStatement createStatement(String sql) throws SQLException{
		return getConnection().preparedStatement(sql);
	}

5、释放资源
	public void close(){
		if(rs!=null){
			try{
				rs.close();
			}catch (SQLException throwables) {
                throwables.printStackTrace();
            }
		}
		if(ps!=null){
			try{
				ps.close();
			}catch (SQLException throwables) {
                throwables.printStackTrace();
            }
		}
		if(conn!=null){
			try{
				conn.close();
			}catch (SQLException throwables) {
                throwables.printStackTrace();
            }
		}
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值