JDBC and jdbc connect to the database
JDBC (java Database Access solution)
JDBC defines a set of standard interfaces. Different database vendors implement these interfaces based on their own database features.
JDBC process:
1) load the driver and establish a connection <br>
2) create a statement object <br>
3) execute the SQL statement <br>
4) processing result set <br>
5) Close the connection <br>
* Main interfaces in JDBC:
* DriverManager: responsible for loading drivers and establishing connections to databases
* Connection: indicates a Connection to the database and is responsible for creating
* Statement
* Statement: executes SQL statements to the database.
* ResultSet: indicates a query result set of the database.
Public class JDBCDemo {<br>
Public static void main (String [] args) {<br>
Try {<br>
// 1: load the driver. The content of different database strings is different. <Br>
Class. forName ("oracle. jdbc. driver. OracleDriver"); <br>
// 2: Use DriverManager to establish a connection with the database through the loaded driver. The static method getConnection of DriverManager is used
To establish a connection with a database, you must input three parameters.
Parameter 1: Database address (different database formats)
Parameter 2: User Name of the database
Parameter 3: Database Password <br>
Connection conn = DriverManager. getConnection (
"Jdbc: oracle: thin: @ 192.168.201.217: 1521: orcl ",
"Openlab ",
"Open123"
);
System. out. println ("connected to the database! ");
// 3: Create a Statement to send an SQL Statement
Statement state = conn. createStatement ();
String SQL = "CREATE TABLE userinfo ("
+ "Id NUMBER (6 ),"
+ "Username VARCHAR2 (50 ),"
+ "Password VARCHAR2 (50 ),"
+ "Email VARCHAR2 (100 ),"
+ "Nickname VARCHAR2 (50 ),"
+ "Account NUMBER (10, 2 )"
+ ")";
// Process the result set
ResultSet rs = state.exe cuteQuery (SQL );
While (rs. next ()){
// Obtain the id
Int id = rs. getInt ("id ");
// Obtain username
String username = rs. getString ("username ");
String password = rs. getString ("password ");
String email = rs. getString ("email ");
String nickName = rs. getString ("nickname ");
Double account = rs. getDouble ("account ");
System. out. println (id + "," + username + "," + password + "," + email + "," + nickName + "," + account );
}
// Close the database connection if there are no other database operations
Conn. close ();
} Catch (Exception e ){
E. printStackTrace ();
}
}
}