I. MySQL database 1. Creating a Database
CREATE DATABASE jdbc CHARACTER SET ‘utf8‘;
2. Build a table
CREATE TABLE user ( id int(10) NOT NULL AUTO_INCREMENT, userName varchar(20) NOT NULL, PRIMARY KEY (id));
3. Add Data
Second, connect MySQL database 1.JDBC URL via JDBC
2.Statement
Boolean execute (String SQL): If the ResultSet object can be retrieved, the returned Boolean value is True, otherwise false is returned. You can use this method to execute SQL DDL statements when you need to use real dynamic SQL.
int executeupdate (String SQL): returns the number of rows affected by the execution of the SQL statement. Using this method to execute an SQL statement, you want to get the number of rows affected, for example, insert,update or DELETE statements.
ResultSet executeQuery (String SQL): returns a ResultSet object. Use this method when you want to get a result set, as if you were using a SELECT statement.
3.ResultSet objects
Execute the SQL statement with the ExecuteQuery () method of the statement object to get the ResultSet object
4. Specific steps and code
Static final String jdbc_driver = "Com.mysql.cj.jdbc.Driver"; static final String db_url = "jdbc:mysql://localhost:3306/ Jdbc?usessl=false "; static final String USER =" root "; static final String PASSWORD =" 123456 ";p ublic static void hello () th Rows ClassNotFoundException {Connection conn = null; Statement stmt = null; ResultSet rs = null; 1. Load driver Class.forName (jdbc_driver); 2. Establish database connection try {conn = drivermanager.getconnection (Db_url, USER, PASSWORD); 3. Execute SQL statement stmt = conn.createstatement (); rs = Stmt.executequery ("Select UserName from user"); 4. Get execution results while (Rs.next ()) {System.out.println ("Hello" + rs.getstring ("UserName")); }} catch (SQLException e) {e.printstacktrace (); } finally {//5. Clean environment try {if (conn! = null) conn.close (); if (stmt! = null) stmt.close (); if (rs! = null) rs.close (); } catch (SQLException e) {E.priNtstacktrace (); } }}
Java Database Development (i)--JDBC connection database