1. Database Integrity
Data integrity constraints are designed to prevent semantically inconsistent data from being present in the database. To maintain data integrity, the semantic constraints added to the database data are data integrity constraints. The mechanism by which DBMS checks whether integrity constraints are met is called integrity checks.
1. Action objects of integrity constraints
Integrity checks are conducted around integrity constraints, so integrity constraints are the core of the integrity checking mechanism.Integrity constraints can act on columns, tuples, and tables.
(1) Column-level constraints
Column-level constraints refer primarily to constraints on the type, range, precision, etc. of a column, including the following:
(1) Constraints on data types;
(2) Constraints on data formats;
(3) Constraints on the range or set of values;
(4) Constraints on null values.
(2) Tuple constraints
Tuple constraints refer to the mutual constraints between fields in an infinite hierarchy.
(3) Table-level constraints
Table-level constraints refer to constraints that relate between tuples and relationships.
2. Define and implement integrity constraints
The integrity rules of a relationship model are some kind of constraint on a relationship. There can be three types of integrity constraints in a relationship model: entity integrity, referential integrity, and user-defined integrity.
(1) Entity Integrity
In MYSQL, entity integrity is achieved through primary and candidate key constraints.
1. Primary Key Constraint
Primary keys can be a column in a table or a combination of columns in a table. Primary keys that combine columns are also called composite primary keys.Primary keys must follow the following rules:
a. Only one primary key can be defined for each table;
b. Key values must uniquely identify each row in the table and cannot be NULL (uniqueness principle);
c. Composite primary keys cannot contain unnecessary extra columns (minimization principle);
d. A column name can only appear once in the list of composite primary keys.
Primary key constraints are implemented using the keyword PRIMARY KEY in two ways: as a column integrity constraint, with keywords appended directly after the column definition, and as a table integrity constraint, with a primary key constraint statement appended after all column definition statements.Composite primary keys can only be used in the second way.After defining the primary key constraint, MYSQL automatically creates a unique index for the primary key, which can either be renamed or PRIMARY by default.
Examples are as follows:
/*Column-level primary key constraint, adding primary key constraint keywords after column definition*/ create table user ( oid int not null auto_increment primary key comment 'Self-adding Primary Key', username varchar(50) not null comment 'User name', pwd varchar(100) not null comment 'User Password' )ENGINE=INNODB; /*Table-level primary key constraint, adding a primary key constraint statement after all column definitions*/ create table user ( oid int not null auto_increment comment 'Self-adding Primary Key', username varchar(50) not null comment 'User name', pwd varchar(100) not null comment 'User Password', primary key (oid) )ENGINE=INNODB; /*Table-level primary key constraints, adding compound primary key constraint statements*/ create table user ( username varchar(50) not null comment 'User name', pwd varchar(100) not null comment 'User Password', sex char(2) not null default 'male' comment 'User gender', primary key (username,sex) )ENGINE=INNODB; /*View user table index after primary key constraint creation*/ show index from user;
(2) Candidate key constraints
Candidate keys are similar to primary keys in that they use the keyword UNIQUE, which differs from primary keys in that:
A. Only one primary key can be defined in a table, but multiple candidate keys can be defined;
b. When a primary key is defined, a PRIMARY KEY index is automatically generated by the system, and when a candidate key is defined, a UNIQUE index is automatically generated.
Examples are as follows:
/*Column-level constraints, adding candidate key constraint keywords*/ create table user ( oid int not null auto_increment primary key comment 'Self-adding Primary Key', username varchar(50) not null unique comment 'User name', pwd varchar(100) not null comment 'User Password' )ENGINE=INNODB; /*Table-level constraints, adding candidate key constraint statements*/ create table user ( oid int not null auto_increment primary key comment 'Self-adding Primary Key', username varchar(50) not null comment 'User name', pwd varchar(100) not null comment 'User Password', unique (username) )ENGINE=INNODB; /*View user table index after primary key constraint creation*/ show index from user;
(2) Referential Integrity
Referential integrity is achieved by defining a foreign key declaration while creating or updating a table.There are two ways to declare a foreign key: one is to add a reference_definition grammar item directly after the column definition, and the other is to add a FOREIGN KEY (index_column_name,...) reference_definition clause after the attribute definitions of all columns.Only foreign key constraints at the table level will take effect in MYSQL.
The reference_definition grammar item is defined as follows:
/*reference_definition grammar item for referential integrity*/ REFERENCES tb_name(index_column_name,...) [ON DELETE reference_option] [ON UPDATE reference_option]
The syntax format of index_column_name is as follows:
column_name [(length)] [ASC|DESC]
The syntax format of reference_option is as follows:
RESTRICT|CASCADE|SET NULL
In the above grammar, the grammar item reference_option is used to specify the implementation policy of the referential integrity constraint. When the implementation policy of the referential integrity constraint is not explicitly indicated, RESTRICT is used by default, which means that the reference column in the reference table refuses to be deleted or updated when the referential column in the reference table is deleted or updated; CASCADE indicates a cascading policy when the referential table is deleted or updated.When a record is deleted or updated in the reference table, the matching record rows are automatically deleted or updated; SET NULL indicates a vacancy policy, and when a record is deleted or updated in the reference table, the related records in the reference table are empty.The following rules also apply when specifying foreign keys:
(1) Referenced tables must have been created (or can be the same table; such tables are called self-reference tables, and this structure is called self-reference structures);
(2) The primary key must be defined for the reference table;
(3) Foreign keys allow a null value, and the contents of the foreign key are correct as long as each non-null value of the foreign key appears in the specified primary key;
(4) The number of columns in a foreign key must be the same as the number of primary key columns in the reference table;
_The data type of the column in the foreign key must be the same as the corresponding data type in the primary key of the reference table.
Examples are as follows:
/*Table-level referencing integrity constraints example with cascading policy for update deletion*/ create table user ( oid int not null auto_increment primary key comment 'Self-adding Primary Key', username varchar(50) not null comment 'User name', pwd varchar(100) not null comment 'User Password', ref_oid int not null comment 'Foreign Key Reference emp Primary Key', foreign key(ref_oid) references emp(empno) on delete cascade on update cascade )ENGINE=INNODB; /*View all foreign keys of the table*/ select * from INFORMATION_SCHEMA.KEY_COLUMN_USAGE where REFERENCED_TABLE_NAME = 'emp';
(3) User-defined integrity
MYSQL supports user-defined integrity constraints, which are non-null, CHECK, and triggers.
1. Non-null Constraints
Non-null constraints restrict a column from being null by adding NOT NULL as a qualifier after its definition.
CHECK Constraints
CHECK constraints allow complex expressions to be used as restrictions, such as subqueries, and CHECK constraints support column- and table-level restrictions.However, the use of CHECK constraints is not supported in MYSQL. The MYSQL storage engine analyzes CHECK statements but ignores CHECK statements, only to improve compatibility.You can use enum or triggers to solve this problem.An example of using enum is as follows:
/*Use enum instead of CHECK check constraints*/ create table user ( oid int not null auto_increment primary key comment 'Self-adding Primary Key', sex enum('male','female') not null default 'male' comment 'User gender' )ENGINE=INNODB;
3. Naming Integrity Constraints
In order to delete and modify integrity constraints, you first need to name them while defining them. Naming integrity constraints is done by adding the keyword CONSTRAINT and the name of the constraint before defining the various integrity constraints. This name must be unique in the database. If it is not given, MYSQL automatically creates one.Examples are as follows:
/*Naming Integrity Constraint Example*/ create table user ( oid int not null auto_increment primary key comment 'Self-adding Primary Key', username varchar(50) not null comment 'User name', pwd varchar(100) not null comment 'User Password', ref_oid int not null comment 'Foreign Key Reference emp Primary Key', constraint user_ref_emp foreign key(ref_oid) references emp(empno) on delete cascade on update cascade )ENGINE=INNODB;
4. Update Integrity Constraints
Integrity constraints cannot be modified directly. To modify an integrity constraint, you actually delete it with an ALTER TABLE statement before adding a new constraint with the same name.An ALTER TABLE statement allows you to delete integrity constraints independently, without deleting the table itself. If you delete a table with a DROP TABLE statement, all integrity constraints in the table are automatically deleted.An example of removing integrity constraints is as follows:
/*Delete foreign keys*/ alter table user drop foreign key user_ref_emp /*Add Foreign Key*/ alter table user add constraint user_ref_emp foreign key(ref_oid) references emp(empno) on delete cascade on update cascade
2. Triggers
Triggers are user-defined event-driven database objects on relational tables and are a way to ensure data integrity.It is mainly used to protect data in tables by implementing complex referential integrity and data consistency that primary and foreign keys cannot guarantee.
1. Create triggers
The syntax for creating triggers is as follows:
CREATE TRIGGER trigger_name trigger_time trigger_event ON tb_name FOR EACH ROW trigger_body
In the syntax above, trigger_time has two options, the keyword BEFORE and the keyword AFTER, to indicate that a trigger is triggered before or after it is activated; trigger_event specifies the trigger event, which can be one of INSERT, UPDATE, DELETE.
Note: Only one trigger is allowed per event in each table, so each table supports up to six triggers.
Examples are as follows:
create table user ( oid int not null auto_increment comment 'Self-adding Primary Key', username varchar(50) not null comment 'User name', pwd varchar(100) not null comment 'User Password', sex char(2) not null default 'male' comment 'User gender', age int comment 'User Age', address varchar(200) comment 'User Address', phone varchar(20) comment 'Telephone', primary key (oid) )ENGINE=INNODB;
/*Example of creating a trigger*/ create trigger tri_user_insert after insert on user for each row set @str = 'A small test'; /*Insert a piece of data into the user table*/ insert into user values(null,'zhangsan','pwd_zhangsan','male',20,null,null); /*Query User Variable Validation Trigger*/ select @str
2. Delete triggers
The syntax for deleting triggers is as follows:
DROP TRIGGER [IF EXISTS] [schema_name.]trigger_name
Examples are as follows:
drop trigger if exists demo.tri_user_insert
Note: When a table is deleted, all triggers on the table are deleted. If you want to modify a trigger, you must delete it before creating it again.(
3. Use triggers
INSERT trigger
Within the INSERT trigger code, a virtual table named NEW can be referenced to access the inserted rows.In the BEFORE INSERT trigger, the values in the NEW can also be updated, allowing changes to the inserted values.Examples are as follows:
/*Create INSERT Trigger*/ create trigger tri_user_insert after insert on user for each row set @str = new.username; /*Insert a piece of data into the user table*/ insert into user values(null,'zhangsan','pwd_zhangsan','male',20,null,null); /*Query User Variable Validation Trigger*/ select @str
DELETE trigger
Within the DELETE trigger code, a virtual table named OID can be referenced to access deleted rows, and the values in OLD are all read-only and cannot be updated.Examples are as follows:
/*Create DELETE Trigger*/ create trigger tri_user_delete after delete on user for each row set @str = old.oid; /*Delete a piece of data from the user table*/ delete from user where username = 'zhangsan'; /*Query User Variable Validation Trigger*/ select @str
UPDATE trigger
Within the UPDATE trigger code, a virtual table named OLD can be referenced to access previous values, or a virtual table named NEW can be referenced to access updated values.In the BEFORE UPDATE trigger, the values in the NEW may also be updated to allow changes to the values that will be used in the UPDATE statement.Only BEFORE UPDATE triggers can be used when triggers involve updating the trigger table itself.Examples are as follows:
/*Create UPDATE Trigger*/ create trigger tri_user_update before update on user for each row set new.pwd = old.username /*Update data in user table*/ update user set pwd = 'wangwu123' where username = 'zhangsan'
3. Security and Access Control
1. User Account Management
View existing users in MYSQL as follows:
select user from mysql.user
(1) Create user accounts
The syntax for creating user accounts is as follows:
CREATE USER user[IDENTIFIED BY [PASSWORD]'password']
In the syntax format above, user specifies the creation of a user account in the format'user_name'@'host_name', user_name denotes the user name, and host_name denotes the host name, which is the host name when MYSQL is connected.If no host name is specified, it is expressed as'%'by default.The keyword PASSWORD is used to specify the hash password (the function PASSWORD() returns the hash value of the password). If the password is set in clear text, the PASSWORD keyword is ignored.Examples are as follows:
/*Query hash values for passwords*/ select password('123'); /*Create two users, one with a clear password and one with a hash password*/ create user 'zhangsan1'@'localhost' identified by '123', 'zhangsan2'@'localhost' identified by password '*23AE809DDACAF96AF0FD78ED04B6A265E05AA257';
Note: If two users have the same user name and different host names, MYSQL treats them as different users and allows different sets of privileges to be assigned to two different users.(
(2) Change user accounts
The grammatical format is as follows:
RENAME USER old_user TO new_user [,old_user TO new_user]...
Examples of use are as follows:
rename user 'zhangsan1'@'localhost' to 'wangwu'@'localhost'
(3) Modify user password
The grammatical format is as follows:
SET PASSWORD [FOR user]={PASSWORD('new_password')|'encrypted password'}
If you want to modify the user's password, you must pass the new password to the PASSWORD() function for encryption or use the encrypted password directly.The optional FOR clause, if not added, modifies the password of the current user, and if added, the password of the specified user.Examples are as follows:
set password for 'wangwu'@'localhost' = '*531E182E2F72080AB0740FE2F2D689DBE0146E04'
(4) Delete user accounts
The grammatical format for deleting user accounts is as follows:
DROP USER user [,user]...
Examples are as follows:
drop user 'wangwu'@'localhost'
2. User Rights Management
After the user is created, the appropriate permissions need to be assigned to the user. The newly created account can only log on to the MYSQL server and cannot perform any database operations.View the user's authorization form as follows:
show grants for 'zhangsan2'@'localhost'
(1) Granting of privileges
Common grammar formats are as follows:
GRANT privi_type [(column_list)] [,privi_type [(column_list)]] ... ON [object_type] privi_level TO user_specification [,user_specification] ... [WITH GRANT OPTION]
In the above grammar format, the grammar item privi_type is used to specify the name of the permission, such as database operations such as SELECT, UPDATE, DELETE; the ON clause is used to specify the object and level to which the permission is granted; and the optional object_type is used to specify the object type to which the permission is granted, including tables, functions, and stored procedures, using the keywords TABLE, FUNCTION, PROCEDURE, respectively.Row identification; the syntax item privi_level is used to specify the level of permissions, * is used to represent all tables in the current database, *. * is used to specify all tables in all databases; the TO clause is used to specify the user and password to grant permissions, the override of which has been specified, and the user is automatically created if it is not present; and the WITH clause is used to implement the transfer or restriction of permissions.
Give users permission to query on certain columns in a table, as shown below:
/*Example of granting users permission to query on some columns in a table*/ grant select(empno,ename) on demo.emp to 'zhangsan2'@'localhost' /*Query empno and ename columns in emp under the zhangsan2 account*/ select empno,ename from demo.emp
Create a new user and set the login password, while granting them SELECT and UPDATE privileges on the emp table, as shown below:
grant select,update on demo.emp to 'zhangsan3'@'localhost' identified by '123'
Grant the user permission to perform all operations in the database, as shown below:
grant all on demo.* to 'zhangsan3'@'localhost'
Grant users the right to create users, for example:
grant create user on *.* to 'zhangsan3'@'localhost'
Additionally, you can refer to the MYSQL website for the use of the grammar item privi_type in GRANT statements: Privileges Provided by MySQL Or refer to the summary of related blogs: Summary of mysql grant user privileges.
(2) Transfer of privileges
The WITH clause implements the transfer of privileges. If the WITH clause is specified as WITH GRANT OPTION, then the users specified in the TO clause have the right to grant their own privileges to other users.Examples are as follows:
/*Create a new user to give it related permissions and allow it to grant its own permissions to other users*/ grant select,update on demo.emp to 'zhangsan4'@'localhost' identified by '123' with grant option
(3) Revocation of privileges
The syntax for recycling permissions is as follows:
REVOKE privi_type [(column__list)] [,privi_type[(column_list)]]... ON [object_type] privi_level FROM user [,user]...
The grammatical format for recycling all permissions is as follows:
REVOKE ALL PRIVILEGES,GRANT OPTION FROM user [,user]...
An example of reclaiming the user's SELECT privileges is as follows:
revoke select on demo.emp from 'zhangsan4'@'localhost'
Note: To use REVOKE statements, you must have global CREATE USER or UPDATE privileges on the database.(
4. Transaction and Concurrency Control
The data in a database is a shared resource, so a database system is usually a multi-user system, that is, it supports multiple different programs or the same program to access the same data in the database concurrently. To prevent them from interfering with each other, so as to ensure that the correctness of the database is not destroyed and data inconsistencies are avoided, this mechanism is called concurrency mechanism.Transactions are a concept and a basic means to ensure data consistency.
1. The concept of transactions
A transaction is a user-defined sequence of data operations that can be performed as a complete unit of work, either wholly or wholly, or as an indivisible unit of work.There are generally three statements in which users explicitly define transactions: BEGIN TRANSACTION, COMMIT, and ROLLBACK.
2. Characteristics of Transactions
Transactions have four characteristics: atomicity, consistency, isolation, and persistence.
_Atomicity
The atomicity of a transaction ensures that a transaction contains a set of operations that are atomically inseparable, that is, a transaction is an indivisible minimum unit of work, and that these operations are a whole, and that the transaction either succeeds or fails to roll back completely when it executes.
(2) Consistency
Consistency requires that transactions must satisfy the integrity constraints of the database, and that the database be transformed from one consistent state to another after the transaction is executed.
(3) Isolation
Isolation requires that transactions be independent and isolated from each other, that is, the execution of one transaction cannot be interfered with by other transactions, and that the result of a transaction's change to the database must be committed before another transaction can be accessed.
When multiple transactions execute concurrently, the result should be equivalent to the result of one of their sequential executions, which is also known as serializability as serial dispatch executes transactions, i.e. any interlaced operation dispatch performed by the system is essentially a serial dispatch, and serial dispatch means that whenever a transaction is dispatched, all operations of the transaction do not endPrevious transactions cannot be performed.
_Persistence
Persistence means that once a transaction is committed, it should make permanent changes to the data in the database, and subsequent operations or failures should not have any impact on its execution results.
3. Concurrent operation problems
Transactions are the basic unit of concurrency control, and the concurrency control mechanism is to schedule concurrent operations in the right way so that the execution of one user transaction is not interfered by other transactions, thus avoiding data inconsistencies.
(1) Dirty reading
Dirty reading refers to reading uncommitted data in one transaction from another.
(2) Non-repeatable reading
Non-repeatable reading refers to multiple queries within a transaction that return different data values for a particular data in the database because, during the query interval, it is modified and committed by another transaction, making it impossible to reproduce the results of the previous read.
(3) Magic reading
Hallucination is a phenomenon that occurs when a transaction executes independently. If a transaction modifies and commits a data item in each row of a data table and another transaction inserts a new unmodified data, if the user of the first transaction looks at the data that has just been modified, he or she will find that there is an unmodified data, which is hallucination.Read.
Magic Read and Non-Repeatable Read are both read from another committed transaction, except that Magic Read reads new data from other transactions, but not changes from other transactions.
4. Four isolation levels
Serializable: can avoid dirty reading, non-repeatable reading, hallucination;
(2) Repeatable read: to avoid dirty and non-repeatable reading;
Read commited: Avoid dirty reading;
Read uncommitted: At the lowest level, nothing can be guaranteed.
The top four isolation levels above are the Serializable level and the lowest are the Read uncommitted level. Of course, the higher the level, the lower the execution efficiency.Levels like Serializable allow other threads to wait outside the lock in a lock table (similar to locks in Java multithreads), so the isolation level you choose in general should be realistic.
In MySQL databases, Repeatable read is the default; in Oracle databases, only Serializable and Read committed levels are supported, with Read committed being the default.
For isolation, you can also refer to:
① Four characteristics of database transactions and isolation level of transactions
② Problems with concurrent database transactions (dirty, non-repeatable, magic, etc.)
5. Blockade
Blockade is the most common concurrency control technology, and its basic idea is that when needed, a transaction locks its desired data object by requesting it from the system to ensure that it does not change unexpectedly.
_Lock
A lock is essentially a privilege that allows or prevents a transaction from accessing a data object.The result of a transaction locking a data object is to block other transactions outside of the object, preventing other transactions from changing the object, while the locked transaction performs the processing it wishes and maintains the correct state of the object.
There are two basic lock types: exclusive and shared.General write operations require exclusive locks, and read operations require shared locks.
(2) Blocked granularity
The size of the blocked data unit is usually described in terms of granularity.DBMS can determine locks of different granularity, lock the whole database, manage and control DBMS is simplest, only one lock needs to be set and tested, so system overhead is minimal. However, access to data can only be done in sequence, so the overall system is greatly reduced. Conversely, data element locks provide the most concurrency, but DBMS sets up a large number of locks to identify those locksCurrently blocked data elements, together with a large number of lock detection, affect the service performance of each transaction, and consequently degrade the overall system performance.Therefore, most high-performance systems choose a compromise lock granularity.
_Live lock and deadlock
In concurrent transaction processing, because locks cause one transaction to wait while other transactions are scheduled, the transaction may wait forever because of its low priority, which is called a "live lock". In the case where more than two transaction cycles wait for a data unit locked by another transaction in the same group, it is called a "deadlock".
There are several ways to prevent deadlocks:
1. One-time lock request
Each transaction makes all lock requests at once, and the transaction will only proceed if the requests are fully satisfied, otherwise it will wait.
(2) Lock Request Sorting
Mark each data unit in a linear order and then require each transaction to make lock requests in that order.
(3) Serialization
The application design establishes a main program for each data unit, all requests for a given data unit are sent to the main program, which runs in a single channel and the system runs in a multiple channel.
4. Deprivation of Resources
Whenever a transaction is blocked due to an unsatisfactory lock request, force one of the two conflicting transactions to ROLLBACK, release all locks, and rerun later (possibly with a live lock).
_Deadlock detection
Once a deadlock has been detected and dealt with, deadlock detection can be implemented in graph theory with the transaction being executed as a node.
_Two-Segment Blockade Method
The two-segment blocking method is a method of scheduling transactions that follow the two-segment blocking protocol, which stipulates that in any transaction, all locking operations must precede all unlocking operations.Transactions are divided into two phases:
(1) Stage of development or lockout
During this period, transactions acquire a corresponding lock on any data object before performing any operation on it.
(2) Contraction or release lock stage
Once a transaction releases a lock, it indicates that it has entered this stage and that it cannot request any additional locks thereafter.
There are the following theorems for two-segment locks:
Any concurrent scheduling of transactions that follow the two-segment lock protocol is serializable.
V. Backup and Recovery
Database backup refers to making a copy of a database by exporting data or copying files; database recovery refers to loading the backed up database into the system when the database fails or is destroyed, thereby restoring the database from an incorrect state to the correct state at the time of backup.The following is an example of a tool class for backup and recovery:
public class DatabaseUtil { public static void main(String[] args) throws Exception{ //Test Backup String command1="mysqldump -hlocalhost -uroot -p123 demo";//Parameters are IP, Account, Password, Database Name in turn String savePath1= "D:/demo.sql"; boolean b1 = new DatabaseUtil().backup(command1, savePath1); System.out.println(b1); //Test Restore String command2="mysql.exe -hlocalhost -uroot -p123 --default-character-set=utf8 demo"; String savePath2= "D:/demo.sql"; boolean b2=new DatabaseUtil().recover(command2, savePath2); System.out.println(b2); } /** * mysql Backup method for * @param command command line * @param savePath Backup Path * @return */ public boolean backup(String command,String savePath) { boolean flag; // Gets the Runtime object associated with the current application Runtime r = Runtime.getRuntime(); try { // Executes the specified string command in a separate process Process p = r.exec(command); // Gets the input stream connected to the normal output of the process, which gets data from the standard output of the process represented by the Process object InputStream is = p.getInputStream(); // InputStreamReader is the bridge from byte stream to character stream: it reads bytes and decodes them into characters using the specified charset InputStreamReader isr = new InputStreamReader(is, "utf-8"); String s; StringBuffer sb = new StringBuffer(""); // BufferedReader reads text from character input streams, buffers characters, provides efficient reading of characters, arrays, and rows BufferedReader br = new BufferedReader(isr); // Assembly String while ((s = br.readLine()) != null) { sb.append(s + "\r\n"); } s = sb.toString(); // Create File Output Stream FileOutputStream fos = new FileOutputStream(savePath); // OutputStreamWriter is a bridge from the character stream to the byte stream, encoding the written characters as bytes using the specified charset OutputStreamWriter osw = new OutputStreamWriter(fos, "utf-8"); // BufferedWriter writes text to the character output stream, buffering characters to provide efficient writing of individual characters, arrays, and strings BufferedWriter bw = new BufferedWriter(osw); bw.write(s); //The following closing method is incorrect, just an example. To keep your program robust, use try...catch bw.flush(); is.close(); isr.close(); br.close(); bw.close(); osw.close(); fos.close(); flag=true; } catch (Exception e) { flag=false; } return flag; } /** * mysql Restore method of * @param command command line * @param savePath Restore Path * @return */ public boolean recover(String command,String savePath) { boolean flag; Runtime r=Runtime.getRuntime(); try { Process p=r.exec(command); OutputStream os=p.getOutputStream(); FileInputStream fis=new FileInputStream(savePath); InputStreamReader isr=new InputStreamReader(fis,"utf-8"); BufferedReader br=new BufferedReader(isr); String s; StringBuffer sb = new StringBuffer(""); while ((s = br.readLine()) != null) { sb.append(s + "\r\n"); } s = sb.toString(); OutputStreamWriter osw = new OutputStreamWriter(os, "utf-8"); BufferedWriter bw = new BufferedWriter(osw); bw.write(s); //The following closing method is incorrect, just an example. To keep your program robust, use try...catch bw.flush(); fis.close(); isr.close(); br.close(); bw.close(); osw.close(); os.close(); flag=true; } catch (IOException e) { flag=false; } return flag; } }