JDBC study notes -MySql

Claim:

  1. Java build a package, the package name of jdbc code database operated "cn.java.dao.impl"

  2. Entity class, package name "cn.java.entity"

  3. Tools, package name "cn.java.utils"

Configure Smart Templates

  1. prompt:

    Windows -> Preferences -> java - > editor -> Content Assist -> - "."> In the second line of the reciprocal after adding A the Z-and 0, 9

  2. Note Templates:

    Windows -> Preferences -> java-> Code Style -> Code Templates -> import -> 导入 -> Windows -> Preferences -> java -> Editor -> Save Actions -> 选中:Format all lines

  3. Format Templates:

    Windows -> Preferences -> java-> Code Style -> Formatter -> import ->

First, preparation

1.1 reflection

### 1.1.1 obtain bytecode document:

  1. Object name .getClass ();

    Class c1 = user1.getClass();

  2. Class name .class;

    Class c2 = User.class;

  3. Class.forName ( "full path byte code");

    Class c3 = Class.forName(路径);

Over 1.2 thread

1.2.1 concept

  1. process:

    Program is being executed

  2. Thread:

    A thread is the process control unit, a process may have multiple threads.

Achieved in two ways 1.2.2 thread

  1. Thread class inheritance:

    The first step: writing an ordinary class, class inheritance thread

    Step: Method override thread class is run, run method task code stored

    The third step: start the thread: object name .start ();

  2. Implement Runnable:

    The first step: writing an ordinary class that implements the interface runnable

    Step Two: Implement run method runnable interface, run task code storage method

    The third step: start the thread: create a Thread object, the object name .start ();

    Test1 test1 = new Test1();
    Test1 test2 = new Test2();
    
    Thread ts1 = new Thread(test1);
    Thread ts2 = new Thread(test2);
    
    ts1.state();
    ts2.state();

1.2.3 The security thread: lock

  1. Conditions occur:

    Operating multiple threads share the same data

  2. Solution:

    A task to complete the locking block

        synchronized(类名.class){

            语句体

        }

Two, SQL language

type of data

  1. Plastic

    1. int

      1. int (m): m represents an expected value, regardless of the size and dimensions of the storage values

      2. zerofill zero padding, will fill in the left 0 (not a data type, can not be used alone)

         eg:
        
         id int(3) zerofill 当输入的id为“1”时,储存为“001”,当输入为“1000”时,zerofill不起作用
        
    2. tinyint: 1 byte

    3. smallint: 2 bytes

    4. bigint: 8 bytes

    5. mediumint: 3 bytes

  2. Float

    1. float

    2. double

  3. Character

    1. char (m): a fixed-length string types, not just a character

    2. varchar (m): a variable-length string type

    3. text: string type large, 4G string

    4. blob: Type Byte

  4. date

    1. date: date type, date

    2. time: type of practice, minutes and seconds

    3. year: Year in

    4. timestamp: year, month, day, hour, time stamp

    5. datetime: year, month, day, hour

Programming language

  1. DDL: Data Definition Language

    1. create

    2. drop

    3. alter

  2. DML: Data Manipulation Language

    1. insert

    2. delete

    3. update

  3. DQL: Data Query Language

    1. select
  4. TCL: Transaction Control Language

    1. commit: commit the transaction

    2. rollback: transaction rollback

    3. savepoint: Transaction Node

  5. DCL: Data Control Language

    1. grant: Authorization

    2. revoke: take-over

2.0 Classification

  1. DQL: Query preload

  2. DML: Manipulation Language

  3. DDL: Definition Language

2.1 library operations

  1. Create a library:

    create database 库名 ;

    Create the specified encoding library:

    create database library name character set encoding name;

    Creating specify the encoding specified sorted set of libraries:

    create database library name character set encoding name collate utf8_general_ci;

  2. Delete a library:

    drop database 库名;

  3. Check the library to create information:

    show create database 库名;

  4. Change encoding library:

    alert database library name character set encoding name;

2.2 Operating Table

  1. Create a table:

    create table 表名(

     字段 数据类型,
    
     字段 数据类型,
    
     primary key(已有字段)【注意:设置主键时,所有的主键为bigint,占20字节,写法:bigint(20)】
    

    );

  2. Delete the table:

    drop table name;

  3. Modify the table:

    1. Modify the table name:

      rename table the old table to the new table name;

    2. Add field:

      alter table Table Field Name Data Type Name add;

    3. Delete field:

      alter table drop table name field name;

    4. Change the field name:

      alter table Old table name field name change column new data type field name;

    5. Modify the field data type:

      alter table table modify the new data type field name;

  4. Lookup table structure (including a table of data type fields and field):

    desc table name;

  5. Lookup table structure (built form of source code):

    show create table 表名;

  6. Copy the table:

    create table table (select * from table);

    Features: There is no primary key and increment

    And add gradually increment:

2.2.1 Other keywords

  1. not null

  2. auto_increment

  3. default defaults

  4. comment comment content

2.3 data manipulation

  1. adding data:

    1. insert into table (field list) value (parameter list);

    2. insert into table parameter set field 1 = 1, 2 ... Field field = 2;

  2. change the data:

    update table set a new value field name = 1, 2 = New field name value where the relational expression

  3. delete data:

    delete from table where conditional expression

    truncate table table name [delete all the data, all the re-entry]

  4. Query data:

    select the field name [[as] alias] from table where conditional expression

2.4 cmd Mysql operation (first path configuration)

  1. See how many libraries:

    show databases;

  2. Use the library (when selected):

    use the table name

  3. View current residence in which library:

    1. select database();

    2. \ S (more comprehensive)

  4. See how many tables:

    show tables;

2.5 MySQL query:

2.5.1 aggregate function

  1. Function call:

    select function name (parameter 1, parameter 2) [Others]

    1. count: count the number of a parameter

      select count (userName) as the number of names from person appear;

      select count (*) as the total number of records from person;

    2. max

    3. me

    4. avg

    5. sum

2.5.2 Common Functions

  1. concat (str1, str2 ... str3): string concatenation

  2. NOW (): Gets the current system time

  3. curDATE (): Get the current date

  4. curDTIME (): Get the current time

  5. rand (): random number fractional

2.5.3 Fuzzy query

select a field name, field name 2 ... from table where field names like conditions; (in% wildcards)

2.5.4 paging query

  1. select * from table limit n(条数)

  2. select * from table limit index,pageSize;

    [Index = (pageNo-1) * afraid of a Size]

2.5.5 Sorting Query

select * from table [Condition] order by sort field desc / asc;

2.5.6 joint inquiry: union

  1. select * from 表1 where id in (1,2,3)

union

select * from 表2 where id in (1,2,3,)

-> query results to weight: identical data only once

  1. select * from 表1 where id in (1,2,3)

union all

select * from 表2 where id in (1,2,3,)

-> Show all results of the query: exactly the same data multiple times;

2.5.7 join queries (interview questions)

  1. En:

    select * from Table 1. Table 1 inner join alias alias 2 ON 2 where connection condition Filters

  2. Outer join

    1. Left connection:

      select * from Table 1 left where an alias filters join Table 2 ON 2 alias connection condition

    2. Right Connections:

      select * from Table 1 1 right where alias filters join Table 2 ON 2 alias connection condition

2.6 custom function

  1. grammar:

    delimiter // [customize the terminator, or SQL default; as a statement terminator, the first statement within the function as a function of body]

    create function function name (parameter type parameter name 1, parameter type name 2 ... Parameter) Returns the data type

    begin

     declare result 返回类型 default 初始值;【声明变量和赋初始值】  
    
     SELECT money INTO ruslt FROM bankaccount WHERE id=ueserId;【变量赋值(实际例子)】  
    

    end//

    DELIMITER; [] will change back terminator

  2. transfer:

    select the function name (arguments);

  3. delete:

    drop function function name;

2.6.1 if

  1. grammar:

    then if the conditional expression

     SQL语句体  
    

    elseif conditional expression then

     SQL语句体  
    

    else

     SQL语句体  
    

    end if

2.6.2 while

  1. grammar:

    while the conditional expression do

     SQL语句  
    

    end while;

2.6.3 switch

  1. grammar:

    case mark

     when 实际 then   
    
         sql  
    
     else    
    
         sql  
    

    end case

2.6.4 increment

  1. grammar:

    set i = i+1;

2.7 storage process

  1. grammar:

    delimiter // [customize the terminator, or SQL default; as a statement terminator, the first statement within the function as a function of body]

    create procedure stored procedure name (parameter type parameter name 1, parameter type name 2 Parameter ...) [not] Return Type

    begin

     declare result 返回类型 default 初始值;【声明变量和赋初始值】  
    
     SELECT money INTO ruslt FROM bankaccount WHERE id=ueserId;【变量赋值(实际例子)】  
    

    end//

    DELIMITER; [] will change back terminator

  2. transfer:

    the name of the stored procedure call (argument);

  3. delete:

    drop procedure stored procedure name

2.8 Triggers

2.9 Constraints

  1. default

  2. not null

  3. unique

  4. primary key

  5. foreign key

  6. check: check constraint (MySQL does not support)

  7. auto_increment

  8. unsigned: Unsigned constraints. When the column specified non-negative value

  9. zerofill: zero padding constraints

Three, JDBC

3.1 database connection

  1. Java SQL server connection

  2. Connect MySQL:

    1. Through third-party connections:

      If the mysql database was closed by sqlyog is not connected, you need to manually open Mysql server: windows + r-> services.msc recall service options

    2. MySQL comes

    3. CMD

3.2 Junit unit testing

When a test method can not only run through:

Write "@Test", will get an error, then put up the mouse, select Junit on that instance methods. Right after the name of the method can be selected to run.

Specification writing

public void 方法名(){代码块}    【没有参数,不能用static】

3.3 JDBC Procedure

  1. Import driver package

    Select the project - "Right -" New - "Folder -" fill in the Folder name at: lib - "copy to lib in the driver package -" The selected drive right package - "Build Path -" Add to Build Path - "in lib file appears above the "small bottle"

  2. Load the driver

    Class.forName(“com.mysql.jdbc.Driver”);

  3. Connect to the database

    DriverManager.getConnerction ( "jdbc: mysql: // localhost: 3306 / database name", user name, password) [package needs to lead, that the election Java.sql]

    Because Java objects that everything in, so the procedure is also connected to the object, called "Connection Object"

  4. Writing SQL statements, execute SQL statements, receiving feedback

    String sql = "the original model as sql statement"

    // Create a car

    Statement st = conn.createStatement();

    // The sql loading, driving

    int result = st.exeuteUpdate(sql);

    if(result >= 1){

     System.out.println("数据添加成功");  
    

    }else{

     System.out.println("数据添加失败");
    

    }

    ResultSet rs = st.executeQuery(sql);

    ResultSet There are two main methods: getObject ()

    The name of the method parameter to be the same as the name of the database table field empty

    If the database is Date type, using the received type String

  5. Close the connection

    st.close();

    conn.close();

3.4 configuration file properties (can not be put under the table)

Storage location: new -> Source Folder -> named conf or resource -> new -> file -> name to ".properties" end

  1. Features:

    1. Only in the form of "key = value" of writing, a line of one pair

    2. Only string type

  2. Read:

    Step 1: Create the properties object that represents the properties file

     1. 将对象与实际内容关联  
    
     2. 将关联后的对象变成流  
    

    Step Two: read data object method

3.5 static block of code (interview point)

  1. grammar

     static {
    
    
    
     }
    
  2. Features: first executed before the constructor

Fourth, the database

4.1 Time conversion functions

  1. grammar:

    date_format(date,format);

    This function type into a string of date

    select date_foramt(publishTime,"%Y/%m%d %H:%i") from goods;

4.2 Transaction (transaction):

  1. Definition: Multi marching as a whole, can not be divided

  2. Steps:

    1. Open transaction: start transaction

    2. [Roll back the transaction: rollback] (only rollback operation before submitting valid)

    3. Commit the transaction: commit

  3. Features:

    1. Atomicity (automic):

      Inseparable between each step

    2. Consistency (consistent):

      The final total operation target unchanged

    3. Isolation (isolation):

      No interference between transactions and transactions.

      There isolation 4z isolation levels: read uncommitted, read committed, repeatable read, serializable (4 levels higher and higher, the level of high-performance worse)

       查看MySQL数据库的隔离级别:select @@tx_isolation;
      
       修改MySQL数据库的隔离级别:set transaction isolation level 隔离级别【一次性】/set all transaction isolation level 隔离级别【永久性】;
      
      1. Dirty read:

        When the isolation level of the database to read uncommitted will lead to dirty read.

        Solution: The isolation of database software to read committed to

      2. Non-repeatable read:

        When the database isolation level is read committed would lead to non-repeatable read.

        Solution: The isolation of database software to as repeatable read

      3. Dummy read (phantom read):

        When the database isolation level is repeatable read will lead to non-repeatable read.

        Solution: The isolation of database software to as serializable

    4. Endurance:

      Once the data is entered into the database, the database needs to ensure data security.

4.3 Database Backup and Restore

  1. Backup:

    1. Third-party software sqlyog

      General sql backup file, the file named "library name + _back"

    2. MySQL command

      mysqldump -u username -p password database name> D: \ database name _back.sql [need to be performed under cmd, can not connect to the database when performing] [need to manually create a restore library]

  2. reduction:

    1. MYSQL command:

      source database backup files need to be performed in the script [cmd, you need to connect to the database when performing]

4.4 MySQL database coding

  1. View:

    show variables like "cha%" wildcards [%]

  2. Change the database code:

    set encoding variable name = name;

4.5 Check performance sql statement

  1. grammar:

    explain sql statement

  2. Methods to improve performance:

    1. To build a field general index

      1. grammar:

        create index index name on table name (field name)

      2. delete:

        drop index index name on table;

    2. Partition table

    3. Use Cached

Five, MD5 encryption

  1. Features:

    1. Take hex

    2. No matter how long the old password, the encrypted into 32 (the number of the intermediate medium 16)

Sixth, stratified

  1. UI layer (interface):

    Package name: cn.java.ui

    There are also packages stored entities: cn.java.entity

    UI layer interfaces calling service layer

  2. service Interface Layer:

    Package name: cn.java.service

  3. the service layer (the layer):

    Package name: cn.java.service.impl

    service layer interface to call dao layer, i.e., interfacial layer

  4. dao Interface Layer:

    Package name: cn.java.dao

    Only put Interface

  5. dao layer:

    Package name: cn.java.dao.impl;

    There is also a package store tools: cn.java.utils

    dao layer mainly operate the database: CRUD, only as an example and the method can not be static

VII Framework BDUtils

  1. Core classes:

    QueryRunner

    When you use objects to create QueryRunner

  2. Query, the query execution method:

    1. query(Connertion conn, String sql, ResultSetHandler rsh):

      The third parameter: indicates what type Returns: 1) Returns an object: new BeanHandler (object class name .class); 2) returns a collection of objects: new BeanListHandler (.class object class name);

    2. query(Connertion conn, String sql, ResultSetHandler rsh,Object…params):

      The fourth parameter is the parameter sql, sql parameters with? instead.

  3. Increase, execute the insert method:

    return

  4. (Increase) excision, perform the update method:

Published an original article · won praise 0 · Views 18

Guess you like

Origin blog.csdn.net/Pytho_Hacker/article/details/104382086