1. Achieve MySql database connection.
The Code is as follows:
Packagetest;
Importjava. SQL. DriverManager;
Importjava. SQL. ResultSet;
Importjava. SQL. SQLException;
Importjava. SQL. Statement;
Publicclassdb {
/**
* @ Paramargs
*/
Publicstaticvoidmain (String [] args ){
// TODOAuto-generatedmethodstub
Stringdriver = "com. mysql. jdbc. Driver"; // method of definition
Stringpath = "jdbc: mysql: // localhost: 3306/buybook"; // define the path (address)
Stringuser = "root"; // define the user name
Stringpwd = "123"; // define the password
ResultSetrt;
Connectioncnn = null;
Statementstatement;
Try {
Class. forName (driver); // obtain the database driver
Cnn = DriverManager. getConnection (path, user, pwd); // obtain the database connection
Statement = cnn. createStatement (); // create an executor
Stringsql = "select * frombooks"; // Add an SQL statement;
Rt1_statement.exe cuteQuery (SQL); // execute the SQL statement and generate the result set
While (rt. next () {// cyclically output the result set
System. out. print (rt. getString ("bno "));
System. out. print ("");
System. out. println (rt. getString ("bname "));
}
} Catch (ClassNotFoundExceptione ){
// TODOAuto-generatedcatchblock
E. printStackTrace ();
} Catch (SQLExceptione ){
// TODOAuto-generatedcatchblock
E. printStackTrace ();
}
Finally
{
Try {
Cnn. close ();
} Catch (SQLExceptione ){
// TODOAuto-generatedcatchblock
E. printStackTrace ();
}
}
}
}
Required knowledge points:
1. next () method: move the cursor backward
2. The DriverManager object (or class) is required for obtaining the Connection object. The getConnection () method of DriverManager creates a connection object through the database Connection url, database username, and password.
3. The Connection interface is located in the java. SQL package.
4. The ResultSet interface is located in the java. SQL package.
5. The Statement interface is located in the java. SQL package.
6. By default, only one ResultSet object can be opened for each Statement object at a time.