Package com.fgy.jdbc; Import the java.sql *. ; public class Demo1Jdbc { public static void main (String [] args) throws a ClassNotFoundException, SQLException { // 1. Import Driver jar package // 2. Registration Driver Class.forName ( "com.mysql.jdbc.Driver" ); // 3. Get connected connection the DriverManager.getConnection = CON ( "JDBC: MySQL: // localhost: 3306 / DB1", "the root", "the root" ); // 4. define the SQL statement String = SQL "SELECT * from STU" ; // 5. The statement object acquired @Statement = con.createStatement the Statement (); the PreparedStatement Statement = con.prepareStatement (SQL); // recommended prepareStatement, SQL injection can be prevented @ 6. execute SQL statements // the ResultSet Statement.executeQuery RS = (SQL); the ResultSet RS = Statement.executeQuery (); // 7. The processing result the while (rs.next ()) { System.out.println (rs.getString ( "name" )); } // 8. The release resources Statement.close () ; con.close (); } }
Package com.fgy.jdbc; Import the java.sql *. ; public class Demo2Jdbc { public static void main (String [] args) { Connection Conn = null ; the PreparedStatement Statement = null ; the try { // 1. Import Driver jar package / / 2. Register drive the Class.forName ( "com.mysql.jdbc.Driver" ); // 3. Get connected conn = DriverManager.getConnection ( "jdbc: mysql : // localhost: 3306 / db1", "root", "root" ); // 4. custom SQL statement String sql = "insert into stu ( name) values ( ' Xiaoxiao')" ; // 5. Obtain statement object statement = conn.prepareStatement (SQL); // 6. The execute SQL statements // Statement.execute (); int I = Statement.executeUpdate (); System.out.println ( "number of rows affected:" + I); // 7. the processing result // ... } the catch (a ClassNotFoundException E) { e.printStackTrace () ; } the catch (SQLException E) { e.printStackTrace (); } the finally { // 8.释放资源 if (statement != null) { try { statement.close(); } catch (SQLException e) { e.printStackTrace(); } } if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } } }