1. Create a connection, download the MySQL driver (JDBC interface implementation class, is a jar package)
public class Demo01 { public static void main (String [] args) throws ClassNotFoundException, SQLException { // 1. registration drive to tell the virtual machine to use database software which Class.forName ( "com.mysql.jdbc.Driver" ); / / 2. Get the connection object connection Conn the DriverManager.getConnection = ( "JDBC: MySQL: // localhost: 3306 / newdb3", "the root", "the root" ); System.out.println(conn); // Create SQL execution object the Statement STAT = conn.createStatement (); // 4. execute SQL statements String SQL = "Create Table jdbct1 (int Primary Key ID, name VARCHAR (10))" ; stat.execute(sql); System.out.println ( "execution is complete!" ); // Close the resource conn.close (); } }
public class Demo02 { public static void main(String[] args) throws ClassNotFoundException, SQLException { Class.forName("com.mysql.jdbc.Driver"); Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/newdb3", "root", "root"); Statement stat = conn.createStatement(); String sql = "drop table jdbct1"; stat.execute(sql); System.out.println ( "execution completed" ); conn.close(); } }
public class Demo03 { public static void main(String[] args) throws ClassNotFoundException, SQLException { Class.forName("com.mysql.jdbc.Driver"); Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/newdb3", "root", "root"); STAT the Statement = conn.createStatement (); // perform additions and deletions to the SQL // String SQL = "INSERT INTO EMP (EMPNO, ename) values (100, 'Tom')"; // String SQL = "Update EMP SET ename = 'Jerry' the WHERE empno = 100 "; // String SQL =" emp the Delete from the WHERE empno = 100 "; // stat.executeUpdate (SQL); // execute the query SQL String SQL =" the SELECT ename, SAL, the Job from emp " ; // query results to put into rs subject the resultSet rs = stat.executeQuery (SQL); // traverse the result set of data objects acquired the while (rs. next()) { //Parameters may be acquired field names and positions String name = rs.getString (. 1 ); Double SAL = rs.getDouble (2 ); String job = rs.getString(3); System.out.println(name+":"+sal+":"+job); } System.out.println ( "successfully executed!" ); conn.close(); } }
2.DBUtil, returns a Connection object
public class DBUtils { public static Connection getConn() throws Exception { Class.forName("com.mysql.jdbc.Driver"); Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/newdb3", "root", "root"); return conn; } }
public class Demo01 { public static void main (String [] args) { // Get connected to the try (Connection Conn = DBUtils.getConn ();) { // create SQL execution object the Statement STAT = conn.createStatement (); // perform SQL String SQL = "the SELECT ename from emp" ; ResultSet rs = stat.executeQuery(sql); while(rs.next()) { String name = rs.getString("ename"); System.out.println(name); } } catch (Exception e) { e.printStackTrace (); } } }
3. Read the properties file
public class Demo02 { public static void main (String [] args) throws IOException { // create a reading profile data object the Properties P = new new the Properties (); // get the file stream the InputStream IPS = Demo02. class .getClassLoader () .getResourceAsStream ( "the jdbc.properties" ); // the file is loaded into attributes object p.load (IPS); // read data String name = p.getProperty ( "name" ); String age = p.getProperty("age"); System.out.println(name+":"+age); } }
4. database connection pool
public class Demo03 { public static void main (String [] args) throws SQLException { // Create a database connection pool object of BasicDataSource DS = new new of BasicDataSource (); // Set the database connection information ds.setDriverClassName ( "com.mysql.jdbc.Driver " ); ds.setUrl("jdbc:mysql://localhost:3306/newdb3"); ds.setUsername("root"); ds.setPassword ( "the root" ); // Set the initial number of connections ds.setInitialSize (. 3 ); // set the maximum number of connections ds.setMaxActive (. 5 ); // get a connection from the connection pool Throws Connection Conn = DS. getConnection (); System.out.println(conn); } }
5.DBUtils, enhanced version
public class DBUtils { private static BasicDataSource ds; static { Properties p = new Properties(); InputStream ips = DBUtils.class.getClassLoader().getResourceAsStream("jdbc.properties"); try { p.load(ips); } catch (IOException e) { e.printStackTrace (); } String driver = p.getProperty("driver"); String url = p.getProperty("url"); String username = p.getProperty("username"); Password String = p.getProperty ( "password" ); // create a database connection pool object ds = new new BasicDataSource (); // Set the database connection information ds.setDriverClassName (driver); ds.setUrl(url); ds.setUsername(username); ds.setPassword(password); // set the initial number of connections ds.setInitialSize (. 3 ); // set the maximum number of connections ds.setMaxActive (. 5 ); } public static Connection getConn () throws Exception { // Get the connection pool Throws Connection Conn = ds.getConnection (); return Conn; } }
6. precompiled
public class Demo04 { public static void main(String[] args) { Scanner s = new Scanner(System.in); System.out.println ( "Please enter your user name" ); String username = s.nextLine(); System.out.println ( "Please enter your password" ); String password = s.nextLine(); //获取连接 try (Connection conn = DBUtils.getConn();) { /*Statement stat = conn.createStatement(); String sql = "select count(*) from user " + "where username='"+username +"' and password='"+password+"'"; // After the test output terminal System.out.println(sql); Rs = stat.executeQuery ResultSet (SQL); * / // solve the SQL injection problem by pre-compiled SQL execution object String SQL = "the SELECT COUNT (*) from the User and the WHERE username = password =??" ; PS PreparedStatement = conn.prepareStatement (SQL); // put? Replaced with real variable ps.setString (. 1 , username); ps.setString(2, password); //执行SQL语句 ResultSet rs = ps.executeQuery(); while(rs.next()) { int count = rs.getInt(1); if(count>0) { System.out.println ( "Login successful!" ); }else { System.out.println ( "Login failed!" ); } } } catch (Exception e) { e.printStackTrace (); } } }
7. bulk operations
public class Demo05 { public static void main(String[] args) { String sql1 = "insert into emp(empno,ename) values(200,'aaa')"; String sql2 = "insert into emp(empno,ename) values(201,'bbb')"; String sql3 = "insert into emp(empno,ename) values(202,'ccc')"; //获取连接 try (Connection conn = DBUtils.getConn();) { STAT the Statement = conn.createStatement (); // add to bulk operations stat.addBatch (sql1); stat.addBatch(sql2); stat.addBatch(sql3); // perform bulk operations stat.executeBatch (); System.out.println ( "execution completed" ); } catch (Exception e) { e.printStackTrace (); } } }
public class Demo06 { public static void main(String[] args) { //create table person(name varchar(10),age int); //获取连接 try (Connection conn = DBUtils.getConn();) { String sql = "insert into person values(?,?)"; PreparedStatement ps = conn.prepareStatement(sql); for (int i = 1; i <= 100; i++) { ps.setString(1, "name"+i); ps.setInt ( 2, C100 + I); // add to bulk operations ps.addBatch (); // to avoid overflow of the memory is performed once every 30 IF (I% 30 == 0 ) { ps.executeBatch(); } } ps.executeBatch (); // perform batch operations } the catch (Exception E) { e.printStackTrace (); } } }
8. Return increment primary key
public class Demo08 { public static void main(String[] args) { Scanner s = new Scanner(System.in); System.out.println ( "Please enter the employee name" ); String name = s.nextLine(); System.out.println ( "Please enter salary" ); int SAL = s.nextInt (); // get a connection the try (Connection Conn = DBUtils.getConn ();) { SQL String = "INSERT INTO myemp values (null,,??)" ; // set up by the primary key value obtained from PreparedStatement PS = conn.prepareStatement (SQL, Statement.RETURN_GENERATED_KEYS); // replace the question mark content ps.setString (1 , name); ps.setInt ( 2 salt); ps.executeUpdate(); System.out.println ( "Save completed!" ); // start increment primary key acquiring the ResultSet RS = ps.getGeneratedKeys (); the while (rs.next ()) { int ID = rs.getInt (. 1 ); System.out.println ( "auto-increment primary key:" + ID); } } catch (Exception e) { e.printStackTrace (); } } }
9. Obtain information about the database itself
public class Demo10 { public static void main (String [] args) { // Get connected to the try (Connection Conn = DBUtils.getConn ();) { // Get metadata object database the DatabaseMetaData DBMD = conn.getMetaData (); System.out.println ( "Database name:" + dbmd.getDatabaseProductName ()); System.out.println ( "Database Driver version:" + dbmd.getDriverVersion ()); System.out.println ( "User Name:" + dbmd.getUserName ()); // get table and related metadata String SQL = "the SELECT * from emp" ; Statement stat = conn.createStatement(); RS the ResultSet = stat.executeQuery (SQL); // Get metadata object the ResultSetMetaData rsmd = rs.getMetaData (); // Get the number of fields int COUNT = rsmd.getColumnCount (); // traverse field names and types for ( int I = 0; I <COUNT; I ++ ) { String name = rsmd.getColumnName(i+1); String type = rsmd.getColumnTypeName(i+1); System.out.println(name+":"+type); } } catch (Exception e) { e.printStackTrace (); } } }