JDBC编程JAVA

学习资料《疯狂java讲义》

环境:MYSQL

        Java 1.7

java用JDBC操作数据库是java编程的基础之一。而掌握SQL是JDBC编程的基础。JDBC是sun公司制定的接口API,各个数据库产商根据接口API提供实现类(驱动程序),这是面向接口编程的典型应用。

可以把 SQL 分为两个部分:数据操作语言 (DML) 和 数据定义语言 (DDL)。

SQL (结构化查询语言)是用于执行查询的语法。但是 SQL 语言也包含用于更新、插入和删除记录的语法。

查询和更新指令构成了 SQL 的 DML 部分:

  • SELECT - 从数据库表中获取数据
  • UPDATE - 更新数据库表中的数据
  • DELETE - 从数据库表中删除数据
  • INSERT INTO - 向数据库表中插入数据

SQL 的数据定义语言 (DDL) 部分使我们有能力创建或删除表格。我们也可以定义索引(键),规定表之间的链接,以及施加表间的约束。

SQL 中最重要的 DDL 语句:

  • CREATE DATABASE - 创建新数据库
  • ALTER DATABASE - 修改数据库
  • CREATE TABLE - 创建新表
  • ALTER TABLE - 变更(改变)数据库表
  • DROP TABLE - 删除表
  • CREATE INDEX - 创建索引(搜索键)
  • DROP INDEX - 删除索引

MYSQL语法:

show databases;

use 数据库名;

show tables;

desc 表名--查看数据表的结构

bin mysql -p 密码 -u 用户名 -h主机名 --default-character-set=utf8  连接远程主机的mysql服务

alter table tablename modify; 只能一次修改一个列

alter table tablename rename to newname;

alter table tablename change 列名 to 新列名 type;

(constraint 约束名)约束定义;---多列约束

primary key( 列名) ----多列主键约束,不能自定义约束名称

列名 type auto_increment primary key---自增长主键

alter table tablename drop index 约束名;

建立外键约束时,MYSQL会为该列建立索引;

列名 类型 references 表名(主键名);

外键参照自身表的主键----自关联

on detete cascade / on delete set null--主键记录删除,从键也删除

create index index_name on table_name (column1, column2...);

create or replace view view_name as subquery  with check option;不允许修改视图数据

DML:

insert into ; update; delete from;

concat("xxx","xxx")字符串连接

distinct、in、like、is null

 PS:不建议在JAVA程序中使用特定数据库的函数,因为会导致程序代码与特定数据库耦合;如果移植要重新打开源程序修改SQL语句。

where 与having的区别

where用于过滤行,having用于过滤组

where子句中不能使用组函数(avg(), count(), max(),min(),sum()),having可以

cross join, natural join, join using, join on

left join, right join ,full join

子查询

集合运算select union/minus/

JDBC常用类和接口:在java.sql包下重要的几个类或对象

DriverManager

Connection

Statement

ResultSet

例子:记得添加mysql -connector-java 的jar包

public class JDBCTest {
    public static void main(String[] args) throws ClassNotFoundException, SQLException, InterruptedException {
        // 加载驱动
        Class.forName("com.mysql.jdbc.Driver");

        try {

            Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/sakila", "root", "password");
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery("select * from city LIMIT 5");
            while (rs.next()) {
                System.out.println(
                        rs.getInt(1) + "	" + rs.getString(2) + "	" + rs.getInt(3) + "	" + rs.getTimestamp(4));
                Thread.sleep(3000);
            }
        } finally {

        }

    }

}

输出:
1    A Corua (La Corua)    87    2006-02-15 04:45:25.0
2    Abha    82    2006-02-15 04:45:25.0
3    Abu Dhabi    101    2006-02-15 04:45:25.0
4    Acua    60    2006-02-15 04:45:25.0
5    Adana    97    2006-02-15 04:45:25.0
//执行SQL,PreparedStatement与Statement对比

public class PreparedStatementTest {
    private String driver;
    private String url;
    private String user;
    private String pass;

    public void initParam(String paramFile) throws Exception {
        Properties props = new Properties();
        props.load(new FileInputStream(paramFile));
        driver = props.getProperty("driver");
        url = props.getProperty("url");
        user = props.getProperty("user");
        pass = props.getProperty("pass");

    }
    public void insertUseStatement() throws Exception
    {
        Class.forName(driver);
        long start = System.currentTimeMillis();
        try(
                Connection conn = (Connection) DriverManager.getConnection(url,user,pass);
                Statement stmt = conn.createStatement())
        {
            for(int i=0;i<100;i++)
            {
                stmt.executeUpdate("insert into student_table values("+"null,'姓名"+i+"', 1)");
            }
            System.out.println("using statement:"+(System.currentTimeMillis()-start));
        }
    }
    //PreparedStatement能防止SQL注入,?代表占位符
    public void insertUsePrepare() throws Exception
    {
        Class.forName(driver);
        long start=System.currentTimeMillis();
        try(
                Connection conn = DriverManager.getConnection(url,user,pass);
                PreparedStatement pstmt=conn.prepareStatement("insert into student_table values(null,?,1)"))
        {
            for(int i =0;i<100;i++)
            {
                pstmt.setString(1,"姓名"+i);
                pstmt.executeUpdate();
            }
            System.out.println(" using PreparedStatement:"+(System.currentTimeMillis()-start));
        }
    }
    

    public static void main(String[] args) throws Exception {
        // TODO Auto-generated method stub
        PreparedStatementTest pt = new PreparedStatementTest();
        pt.initParam("E:\workspace\learning\mysql.ini");
        pt.insertUseStatement();
        pt.insertUsePrepare();

    }

}

输出:
using statement:3423
 using PreparedStatement:3176
View Code
原文地址:https://www.cnblogs.com/flyingbee6/p/5149772.html