java web学习第二十五天——mysql

Day25

约束

外键:

必须是另一张表的主键;外键可以重复,可以为空;一张表可以有多个外键

Constraint  fk_dept foreign key(外键) preferences表名(主键)

 

多表查询:

1.     合并结果集(表之间必须列相同,类型相同)

Select * from ab union (all不去除重复) select * from cd

链接查询

内连接:select * from 1 别名1 innerjoin2 别名2 on主键相等;

外连接:select * from 1 别名1 leftright outer join2 别名2 on主键相等;(左外连接左表为主,主表中的所有记录无论满足不,都打印,不满足时右表null来补位)

 

子查询(select不止一个)

1select出现的位置

  where之后:多行一列,一行多列

              where之后的查询结果是多行一列的集合是可以使用allany

  from之后:多行多列

分析问题:

先查看结果集都需要哪一些列,然后查看需要哪些表,最后看条件;

 

JDBC

导包jar

连接数据库:

Class.forName("com.mysql.jdbc.Driver");//加载驱动类

       String url="jdbc:mysql://localhost3306/shujuku1";

       String username="root";

       String password="123";

       Connectioncon

= DriverManager.getConnection(url,username,password);

//使用DriverManger得到Connection

 

容易出现的异常:com.mysql.jdbc.exceptions.jdbc4.CommunicationsException:Communications link failure

这是连接错误,是由于没有导包或者找不到com.mysql.jdbc.Driver

 

其他错误(SQLException)都是由于URL没有写对导致的;

对数据库进行增,删,改操作:

//利用Connection得到Statement是用来加载SQL语句的

Statement stam =con.createStatement();

Int I = stam.executeUpdate(“SQL语句”);返回影响的行数

对数据库进行查询操作:

ResultSet re = stam.executeQuery(“sql语句”);

返回的结果集中的函数有:

next():是光标向下一行移动

re.getInt(n):通过列的编号来得到该列的值

re.getString(“列名”):通过列名来得到该列的值

re.getObject(“列名”):

re.getDouble():

 

获取结果集数据:

1. 得到元数据 re.getMetaData();返回值为:ResultMataData;

2. 其中方法有:int getColumnCount()得到结果集列数

3. String getColumnNameint colindex)给句列数得到列名;

4. 例子

Statement stat = con.createStatement();

       ResultSet re = stat.executeQuery("select * from book");

       intcount = re.getMetaData().getColumnCount();//得到列数

       while(re.next()){

           for(inti = 1 ; i<=count;i++){

              System.out.print(re.getString(i));

              if(i!=count){

                  System.out.print(",");

              }

           }

           System.out.println();

结果集的特性:当使用Connection得到createStatement的时候,就确定了statement生成的结果集是什么特性了。

是否可以滚动

是否敏感

是否可更新

Con.createStatement(int,int );

第一个参数:。。。了解

 

PreparedStatement

1 他是statement的子接口

 功能:String sql="select* from book where id=? and bName=?";

       PreparedStatement pre = con.prepareStatement(sql);

       //为参数赋值

       pre.setString(1, username);

       pre.setString(2, password);

       ResultSet re = pre.executeQuery();//无参数

       returnre.next();

 

预处理的原理:

1.校验SQL语句的语法

2.编译

3.执行

前提:连接的数据库支持预处理

每个pre都和SQL模板绑在一起,先把SQL模板给数据库,数据库先进行校验,在进行编译,执行时只不过是把参数传递过去。若二次执行是就不用再检验语法了,也不用再次编译,直接执行。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值