Basic jdbc (I) simple use of MySQL and basic jdbc mysql
JDBC can be used to establish a connection with the database, send statements for database operations, and process the results.
The first thing the program needs to do is to load the database driver. Here I am using mysql:
1 String driverName=new String("com.mysql.jdbc.Driver");2 Class.forName(driverName);
Then obtain the database connection object. The parameter is the database url, user name, and password. Here, the name of the database I used is jdbc, And the username is root. The password is 123456:
1 String url=new String("jdbc:mysql://localhost:3306/jdbc");2 String user=new String("root");3 String password=new String("123456");4 Connection coon=DriverManager.getConnection(url, user, password);
To operate the database, you need to obtain the Statement object:
1 Statement statement = connection.createStatement();
The execute (String SQL) method encapsulated in the statement object, the executeQuery (String SQL) method, and the executeUpdate (String SQL) method can be used to execute SQL statements to perform database operations.
1 String SQL = null; 2 ResultSet resultSe = null; 3 4 // create Student table 5 SQL = "create table Student (id char (9) primary key, name char (9) unique) "; 6 statement.exe cute (SQL); 7 8 // Add tuples 9 SQL =" insert into Student (id, name) values ('20170101', 'hangsan ') "; 10 statement.exe cuteUpdate (SQL); 11 12 // query Student Table 13 SQL =" select * from Student "; 14 resultSet = statement.exe cuteQuery (SQL ); 15 16 while (resultSet. next () {17 System. out. println ("name:" + resultSet. getString ("name"); 18 System. out. println ("id:" + resultSet. getString ("id"); 19} 20 21 // delete the tuples 22 SQL = "delete from Student where id = '000000'"; 23 statement.exe cuteUpdate (SQL ); 24 25 // Delete the table Student26 SQL = "drop table Teacher"; 27 statement.exe cute (SQL );
After the database is operated, you must close the resources in sequence: resultSet, statement, and connection:
1 try { 2 if (resultSet != null) 3 resultSet.close(); 4 } catch (SQLException e) { 5 e.printStackTrace(); 6 } finally { 7 resultSet = null; 8 try { 9 if (statement != null)10 statement.close();11 } catch (SQLException e) {12 e.printStackTrace();13 } finally {14 statement = null;15 try {16 if (connection != null)17 connection.close();18 } catch (SQLException e) {19 e.printStackTrace();20 } finally {21 connection = null;22 }23 }24 }
Close () throws an exception and requires a try/catch Block. To ensure resource release, you need to put the call of the close () method in the finally statement block and determine whether the object is null before releasing the resource. So far, it is complete to connect to the database using jdbc.