Before the text
Using JDBC in the previously written Javaweb project, here's a recap and a demo look at the JDBC concept first.
A Java database connection, (Java db Connectivity, or JDBC) is an application interface in the Java language that regulates how a client program accesses a database, providing methods such as querying and updating data in a database??????????? --wikipedia
Body 1. Preparatory work
2. Defining Database Information
//数据库地址 private static final String url = "jdbc:mysql://localhost:3306/customer"; private static final String name = "com.mysql.jdbc.Driver"; private static final String username = "这里填上你的数据库名称"; private static final String password = "这里填上你的数据库的密码";
3. Turn on the connection
private DBManager(String sql){ try{ Class.forName(name); connection = DriverManager.getConnection(url, username, password); preparedStatement = connection.prepareStatement(sql); }catch(Exception e){ e.printStackTrace(); } }
4. Close connection required after operation
private void close(){ try{ this.connection.close(); this.preparedStatement.close(); }catch (Exception e){ e.printStackTrace(); } }
5. Write a demo
public static void Main (string[] args) {String sql = ' SELECT * from Customer '; DBManager DBManager = new DBManager (SQL); Instantiate String ID, name, gender, phone, email, description; try{ResultSet result = DbManager.preparedStatement.executeQuery (); while (Result.next ()) {//If there is data, the output id = result.getstring (1); Name = Result.getstring (2); Gender = result.getstring (3); Phone = result.getstring (4); email = result.getstring (5); Description = result.getstring (6); Displays each row of data System.out.println (ID + "+ name +" "+ Gender +" "+ Phone + "+ email +" + description); } result.close (); Dbmanager.close (); }catch (Exception e) {e.printstacktrace (); } }
6. Complete code
7. Query Results
Jdbc:
MySQL Workbench:
The result is the same, proving that the JDBC connection to the database and the operation succeeded
"Javaweb" JDBC Connection MySQL Database