Step 1: introduce required packages, such as java. SQL. *, javax. SQL. *; Step 2: load the driver; Class. forName (StringclassName); Note: Another method is DriverManager. registerDriver (new Driver Class Name () (such as OracleDriver (); this method is not recommended in actual development.
Step 1: introduce required packages, such as java. SQL. *, javax. SQL. *; Step 2: load the driver; Class. forName (String className); Note: Another method is DriverManager. registerDriver (new Driver Class Name () (such as OracleDriver (); this method is not recommended in actual development.
Procedure
Step 1: introduce the required package;
For example, java. SQL. *, javax. SQL .*;
Step 2: load the driver;
Class. forName (String className );
Note: Another method is DriverManager. registerDriver (new Driver Class Name () (such as OracleDriver (); this method is not recommended in actual development. This method causes the driver to be loaded twice, resulting in low efficiency.
Step 3: Obtain the connection to the database;
Connection conn = DriverManager. getConnection (String url, String user, String password );
Note: Obtain the database connection according to the url. the user is the username used to log on to the database, and the password is the login password.
Database url Description: The url is written as: localhost can be replaced by the return address 127.0.0.1 pointing to the Local Machine
Common Database url:
Oracle -- jdbc: oracle: thin: @ localhost: 1521: sid
SqlServer -- jdbc: microsoft: sqlserver: // localhost: 1433; DatabaseName = sid
MySQL -- jdbc: mysql: // localhost: 3306/sid
Step 4: Create an object for sending SQL statements;
Statement statement = conn. createStatement ();
Note:
There are three types available:
① Statement: this class is the most primitive and common and can be used for crud operations. However, the injection vulnerability may occur in query operations;
② PrepareStatement: SQL statements can be pre-processed and the set method provided by SQL statements can be used to prevent injection vulnerabilities, which is highly secure and reliable;
③ CallableStatement: used to call a stored procedure;
Step 5: Send SQL statements to the database through statement;
Statement.exe cuteUpdate (String SQL); // executeUpdate () is used to execute INSERT, UPDATE, DELETE or DDL statements. A result is returned to indicate the number of rows affected by the SQL statement.
Statement.exe cuteQuery (String SQL); // executeQuery () is used to execute the SELECT statement. A result set ResultSet is returned and the structure needs to be processed.
Step 6: disconnect from the database and Release relevant resources (close the database based on the principle of first opening and then closing );
Note: The entire database processing statement will throw an exception, so use try catch block to pack it, and write the closed connection statement in the finally block after the block.