Forgive me is a beginner, this method write sucks, future will not improve, thank you
/*** Insert a data into the database using JDBC 1.Statement object 1.1 for executing SQL statements 1.2 through the connection * createstatement () method to get through the executeupdate (SQL) method to execute SQL 1.3 * Incoming SQL can be insert/update/delete, but cannot be select * * 2.Connection and statement after use must remember to close required in Finall Y to close its object * 2.1 The order of closing: first closed after getting the*/@Test Public voidteststatement () {//1. Get a database connectionConnection Connection =NULL; //4. Perform the Insert//4.1 Gets the statement object that operates the SQL statement://Call Connection's createstatement () method to create an statement objectStatement Statement =NULL; Try{Connection=getconnection (); //3. Preparing the inserted SQL statementString sql = "INSERT into Customers (Name,email,birth)" + "VALUES" (' Bruce Lee ', ' [EMAIL protected] ', ' 1940-11- 27 ') "; Statement=connection.createstatement (); //4.2 Calling the statement object's executeupdate (SQL) to execute an insert of the SQL statementstatement.executeupdate (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 the connection Try{connection.close (); } Catch(SQLException e) {e.printstacktrace (); } } } } PublicConnection getconnection ()throwsException {//four strings ready to connect to a database//full class name of the driveString Driverclass =NULL; String Jdbcurl=NULL; String User=NULL; String Password=NULL; String Jdbcname=NULL; //Read Jdbcname.properties fileInputStream instream = GetClass (). getClassLoader (). getResourceAsStream ("Properties/jdbcname.properties"); Properties Propertiesofname=NewProperties (); Propertiesofname.load (instream); Jdbcname= Propertiesofname.getproperty ("Jdbcname"); //read the desired properties fileInputStream in = GetClass (). getClassLoader (). getResourceAsStream ("properties/" + Jdbcname + ". Properties"); Properties Properties=NewProperties (); Properties.load (in); Driverclass= Properties.getproperty ("Driver"); Jdbcurl= Properties.getproperty ("Jdbcurl"); User= Properties.getproperty ("User"); Password= Properties.getproperty ("Password"); //Load Database driver (register driver)Class.forName (Driverclass); Connection Connection=drivermanager.getconnection (jdbcurl, user, password); returnconnection; }
The database is configured as follows
Insert a single piece of data into the database using JDBC