Insert a piece of data into the database using JDBC.
Forgive me for being a beginner. This method is poorly written and will not be improved in the future. Thank you.
/*** Insert a piece of data into the database through JDBC. statement: the object used to execute the SQL Statement. 1.1 is obtained through the * createStatement () method of the Connection. 1.2 is obtained through executeUpdate (SQL) to execute SQL 1.3 * The input SQL can be INSERT/UPDATE/DELETE, but not SELECT ** 2. after Connection and Statement are used, remember to close the order of closing the object * 2.1 in finally: The */@ Test public void testStatement () obtained after closing the object first () {// 1. obtain database Connection connection = null; // 4. execute insert // 4.1 to obtain the Statement object of the SQL Statement: // call createStateme of Connection The object Statement = null; try {connection = getConnection (); // 3. prepare the inserted SQL statement String SQL = "INSERT INTO MERs (NAME, EMAIL, BIRTH)" + "VALUES ('Bruce Lee ', 'long @ live.com', '2017-11-27 ') "; statement = connection. createStatement (); // 4.2 call the executeUpdate (SQL) of the Statement object to execute the SQL Statement insert statement.exe cuteUpdate (SQL);} catch (SQLException e) {e. printStackTrace ();} catch (Exception e) {E. printStackTrace ();} finally {// 5. Close the Statement object if (statement! = Null) {try {statement. close () ;}catch (SQLException e) {e. printStackTrace () ;}} if (connection! = Null) {// 2. close connection try {connection. close ();} catch (SQLException e) {e. printStackTrace () ;}}} public Connection getConnection () throws Exception {// four strings to connect to the database // The full-class name of the driver String driverClass = null; string jdbcUrl = null; String user = null; String password = null; String jdbcName = null; // read jdbcName. properties file InputStream inStream = getClass (). getClassLoader (). getResourceAsStream ("properties/jdbcName. properties "); Properties propertiesOfName = new Properties (); propertiesOfName. load (inStream); jdbcName = propertiesOfName. getProperty ("jdbcName"); // read the required properties file InputStream in = getClass (). getClassLoader (). getResourceAsStream ("properties/" + jdbcName + ". properties "); Properties properties = new Properties (); properties. load (in); driverClass = properties. getProperty ("driver"); jdbcUrl = properties. getProperty ("jdbcUrl"); user = properties. getProperty ("user"); password = properties. getProperty ("password"); // load the database Driver (register the driver) Class. forName (driverClass); Connection connection = DriverManager. getConnection (jdbcUrl, user, password); return connection ;}
The database configuration is as follows: