First, we need to understand the concept of JDBC.
JDBC (Java database Connectivity) is a set of database programming APIs available in Java that defines a standard Java class library (in java.sql and javax.sql packages) to access the database. Using JDBC, we can write programs in Java, implement a connection with a particular database, send SQL statements to the database, implement specific operations on the database, and process the results returned by the database.
JDBC programming typically consists of the following six steps:
1. Select the JDBC driver type according to the database used by the application.
2. Connect to the database and get the connection object.
3. Create a statement object from connection.
4. Submit the SQL statement using the Stateme object.
5. Operation result set.
6. Reclaim database resources.
The code is as follows:
PackageSqlpractice;Importjava.sql.Connection;ImportJava.sql.DriverManager;ImportJava.sql.ResultSet;Importjava.sql.SQLException;Importjava.sql.Statement; Public classFirst {/** * @paramargs*/ Public Static voidMain (string[] args) {Connection conn=NULL;//Connection ObjectStatement stat =NULL;//Statement ObjectResultSet ResU =NULL;//Query Result set /*JDBC Development Steps*/ //The first step is to add the driver package to the build path//Second Step load driver Try{class.forname ("Com.mysql.jdbc.Driver"); } Catch(ClassNotFoundException e) {e.printstacktrace (); } //Step three Create the Connection objectString url = "Jdbc:mysql://localhost:3306/jdbc"; //User nameString user = "root"; //PasswordString Password = "* * *"; Try{conn=drivermanager.getconnection (URL, user, password); } Catch(SQLException e) {e.printstacktrace (); } //Fourth Step Create statement object Try{stat=conn.createstatement (); } Catch(SQLException e) {e.printstacktrace (); } //Fifth Step Send SQL statementString sql = "SELECT * from User"; Try{ResU=stat.executequery (SQL); } Catch(SQLException e) {e.printstacktrace (); } //Sixth step processing results Try { while(Resu.next ()) {System.out.println ("\n\t User id:" + resu.getstring ("id") + "Username:" + resu.getstring ("username") + "Password:" + resu.getstring ("password")); } } Catch(SQLException e) {e.printstacktrace (); } //Seventh Step release Resources if(Conn! =NULL) { Try{conn.close (); } Catch(SQLException e) {e.printstacktrace (); } } if(Stat! =NULL) { Try{stat.close (); } Catch(SQLException e) {e.printstacktrace (); } } if(ResU! =NULL) { Try{resu.close (); } Catch(SQLException e) {e.printstacktrace (); } } }}
"Java Database Programming"