Java database connection process:
Step 1: Install the driver and set the path
Step 1: To mysqlofficial website download mysql-connector-java-5.0.8.zip driver, decompress the copy inside the mysql-connector-java-5.0.8.jar to JDK installation directory lib folder;
Step 2: Set the environment variable classpath =.; % java_home %/lib/mysql-connector-java-5.0.8.jar;
Step 2: Programming
Step 1: load and register the JDBC driver in the program, where the JDBC-ODBC comes with JDK, the default has been registered, so do not need to register;
Class. forname ("com. MySQL. JDBC. Driver ");
Java. SQL. drivermanager. registerdriver (new COM. MySQL. JDBC. Driver (); // not required for MySQL
Step 2: establish a connection with the database
Connection con = java. SQL. drivermanager. getconnection (dburl, user, PWD );
Dburl indicates the jdbc url to connect to the database: JDBC: mysql: // localhost: 3306/db_name
User: Database User Name
PWD: Database Password
Step 3: Create a statement object and prepare to execute an SQL statement.
Statement stmt = con. createstatement ();
Step 4: Execute SQL statements
String SQL = "select * From tb_name ";
Resultset rs = stmt.exe cutequery (SQL );
Step 5: traverse records in the resultset object
While (Rs. Next ()){
String name = Rs. getstring (INDEX );
Long id = Rs. getlong (INDEX );
Int age = Rs. getint (INDEX );
}
Step 6: Close the database
Rs. Close ();
Stmt. Close ();
Con. Close ();