1. Database driver
A program between Java programs and MySQL.
2.JDBC
In order to simplify the operation of developers, Sun provides a specification (of Java operating database), commonly known as JDBC. The implementation of these specifications is done by specific vendors.
For developers, only need to master the operation of the JDBC interface. The JDBC program is somewhere between the database driver and the application program.
3. The first JDBC program
preliminary work:
1. Create an ordinary Java project
3. Copy the mysql database driver jar package to the lib folder
4. Right-click the lib folder and select add as library, which means that the driver package was successfully imported
Summary of steps to connect to the database :
1. Load the driver
2. Connect to the database DriverManager
3. Obtain the Statement of the object that executes SQL
4. Get the returned result set
5. Release the connection
DriverManager
DriverManager.registerDriver ( new new com.mysql.jdbc.Driver ()) the Class.forName ( "com.mysql.jdbc.Driver ()" ); / * the role of the above two lines are the same, the first By passing a driver object to the DriverManager.registerDriver method * // // DriverManager.registerDriver method source code is as follows public static synchronized void registerDriver (java.sql.Driver driver) throws SQLException { registerDriver (driver, null ); } // its internal The source code of the registerDriver method is as follows public static synchronized void registerDriver (java.sql.Driver driver, DriverAction da) throws SQLException { /* Register the driver if it has not already been added to our list */ if(driver != null) { registeredDrivers.addIfAbsent(new DriverInfo(driver, da)); } else { // This is for compatibility with the original DriverManager throw new NullPointerException(); } println("registerDriver: " + driver); } // 再来看一下com.mysql.jdbc.Driver()的源码 public classDriverextendsNonRegisteringDriver implements java.sql.Driver { public Driver () throws SQLException { } static { try { DriverManager.registerDriver ( new Driver ()); } catch (SQLException var1) { throw new RuntimeException ("Can't register driver!" ) ; } } } / * You can see that there is a static code block inside. When the class is loaded, this static code block will be executed. This static code block is also the DriverManager.registerDriver method that is executed , and a drive object is passed. , So the essence of the above two ways to load the driver is the same * / = Connection connection DriverManager.getConnection (url, username, password); // connection represents the database // database settings are automatically submitted connection.setAutoCommit () // transaction commit connection.commit () // transaction rollback connection.rollback ()
URL
String url = "jdbc: mysql: // localhost: 3306 / jdbcstudy? UseUnicode = true & characterEncoding = utf8 && useSSL = false" ; // jdbc: mysql: // Host address: port / database name? Parameter 1 & Parameter 2 ...
Statement executes SQL objects, PrepareStatement executes SQL objects
String sql = "select * from users" ; Statement statement = connection.createStatement (); statement.execute (); statement.executeQuery (); // Query operation returns a result set ResultSet statement.executeUpdate (); // Update, Insert and delete use this method, it will return an affected number of rows // 5. Execute SQL object to execute SQL, if there is a result, view the returned result
ResultSet
Get the specified data type
ResultSet resultSet = statement.executeQuery (sql); // The result set encapsulates the results of all of our queries // If the type of the field to be obtained is specified, specify the type, otherwise it is to getObject method resultSet.getObejct (); resultSet .getString (); resultSet.getInt (); resultSet.getDate ();
Traverse, pointer
resultSet.beforeFirst () // Move to the front resultSet.afterLast () // Move to the last resultSet.next () // Move the next data resultSet.previous () // Move to the previous row resultSet.absolute (row) // Move to the specified line
Free up resources
resultSet.close();
statement.close();
connection.close();
4.Statement object
The Statement object in JDBC is used to send SQL statements to the database . If you want to complete the addition, deletion, and modification of the database, you only need to send the addition, deletion, and modification query to the database through this object.
The executeUpdate method of the Statement object is used to send SQL statements that are added, deleted, or modified to the database. After the execution of executeUpdate is completed, an integer will be returned (that is, the addition, deletion, and modification of the statement causes several rows of data in the database to change).
The Statement.executeQuery method is used to send query statements to the database, and the executeQuery method returns a ResultSet object representing the query result.
CRUD operation-insert
Use the executeUpdate (String sql) method to complete the data addition, example operation:
Statement st = conn.createStatement(); String sql = "insert into user(....) values(....)"; int num = st.executeUpdate(sql); if(num > 0){ System.out.println("插入成功!!") }
CRUD operation-delete
Use the executeUpdate (String sql) method to complete the data deletion operation, example operation:
Statement st = conn.createStatement(); String sql = "delete from user where id=1"; int num = st.executeUpdate(sql); if(num > 0){ System.out.println("删除成功!!") }
CRUD operation-update
Use the executeUpdate (String sql) method to complete the data modification operation, example operation:
Statement st = conn.createStatement(); String sql = "update user set name= '' where name = '' "; int num = st.executeUpdate(sql); if(num > 0){ System.out.println("修改成功!!") }
CRUD operation-read
Use the executeQuery method to complete the data query operation, example operation:
Statement st = conn.createStatement (); String sql = "select * from user where id = 1" ; ResultSet rs = st.executeQuery (sql); while (rs.next ()) { // According to the data type of the obtained column , Respectively call the corresponding method of rs mapped to java object }
4. Standardized implementation
1. Write a configuration file db.properties in the src folder, used to save the key information to connect to the database;
The contents are as follows:
driver = com.mysql.jdbc.Driver url = jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf8&&useSSL=false username = 用户名 password = 密码
2. Create a new utils package to store the tool class for connecting to the database. The code of this tool class is implemented as follows:
public class jdbcUtils { private static String driver = null; private static String url = null; private static String username = null; private static String password = null; static { try{ InputStream in = jdbcUtils.class.getClassLoader().getResourceAsStream("db.properties"); Properties properties = new Properties(); properties.load(in); driver = properties.getProperty("driver"); url = properties.getProperty("url"); username = properties.getProperty("username"); password = properties.getProperty("password"); //1.驱动只用加载一次 Class.forName(driver); }catch (Exception e){ e.printStackTrace(); } } // 获取连接 public static Connection getConnection() throws SQLException { return DriverManager.getConnection(url,username,password); } // 释放连接资源 public static void relese(Connection conn, Statement st, ResultSet rs){ if (rs!=null){ try{ rs.close(); }catch (SQLException e) { e.printStackTrace(); } } if (st!=null){ try{ st.close(); }catch (SQLException e) { e.printStackTrace(); } } if (conn!=null){ try{ conn.close(); }catch (SQLException e) { e.printStackTrace(); } } } }
3. Write the code of the specific operation database in other specific business packages
Increase operation:
public class jdbctest02 { public static void main (String [] args) { Connection Conn = null ; the Statement ST = null ; the ResultSet RS = null ; the try { Conn = jdbcUtils.getConnection (); // get a database connection st = conn. createStatement (); // Get the SQL execution object String sql = "insert into users values (4, 'lalal', '123456', '[email protected]', '2020-01-01')" ; int i = st.executeUpdate(sql); if (i>0){ System.out.println("插入成功"); } } catch (SQLException e) { e.printStackTrace(); }finally { jdbcUtils.relese(conn,st,rs); } } }
Delete operation:
public class jdbctest03 { public static void main (String [] args) { Connection Conn = null ; the Statement ST = null ; the ResultSet RS = null ; the try { Conn = jdbcUtils.getConnection (); // get a database connection st = conn. createStatement (); // Get the SQL execution object String sql = "delete from users where id = 4" ; int i = st.executeUpdate (sql); if (i>0){ System.out.println("删除成功"); } } catch (SQLException e) { e.printStackTrace(); }finally { jdbcUtils.relese(conn,st,rs); } } }
Modify operation:
public class jdbctest04 { public static void main (String [] args) { Connection Conn = null ; the Statement ST = null ; the ResultSet RS = null ; the try { Conn = jdbcUtils.getConnection (); // get a database connection st = conn. createStatement (); // Get SQL execution object String sql = "update users set name = 'Kukaka' where id = 1" ; int i = st.executeUpdate (sql); if (i>0){ System.out.println("修改成功"); } } catch (SQLException e) { e.printStackTrace(); }finally { jdbcUtils.relese(conn,st,rs); } } }
Query operation:
public class jdbctest05 { public static void main (String [] args) { Connection Conn = null ; the Statement ST = null ; the ResultSet RS = null ; the try { Conn = jdbcUtils.getConnection (); // get a database connection st = conn. createStatement (); // Get the SQL execution object String sql = "select * from users" ; rs = st.executeQuery (sql); while (rs.next()){ System.out.println("id="+rs.getObject("id")); System.out.println("name="+rs.getObject("name")); System.out.println("pwd="+rs.getObject("password")); System.out.println("email="+rs.getObject("email")); System.out.println("birthday="+rs.getObject("birthday")); } } catch (SQLException e) { e.printStackTrace(); }finally { jdbcUtils.relese(conn,st,rs); } } }