Java database connection requires the use of classes and methods in the java.sql package, including: DriverManager: manages the database driver and establishes a connection with the database. Connection: Represents the connection to the database. Statement: The object that executes the SQL statement. ResultSet: Object that stores query results.
Common classes and methods for Java database connection
To connect to the database in Java, you need to use the java.sql
package classes and methods in . The following introduces several common classes and methods:
Class:
-
DriverManager: Manage the database driver and establish a connection with the database .
-
Connection: represents the connection to the database.
-
Statement: The object that executes the SQL statement.
-
ResultSet: Object that stores query results.
Method:
-
DriverManager.getConnection(String url, String user, String password): Get and specify the database Connection.
-
Connection.createStatement(): Create a Statement object.
-
Statement.executeUpdate(String sql): Execute SQL statements that update the database, such as INSERT, UPDATE, and DELETE.
-
Statement.executeQuery(String sql): Execute the SQL statement that queries the database, and the results are saved in ResultSet.
-
ResultSet.next(): Move the cursor to the next line.
-
ResultSet.getString(String columnName): Get the string value of the specified column name.
-
ResultSet.getInt(String columnName): Get the integer value of the specified column name.
Practical case:
Connect to MySQL database and query a table:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | import java.sql.*;
public class JdbcExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/database_name" ;
String user = "username" ;
String password = "password" ;
try {
Connection connection = DriverManager.getConnection(url, user, password);
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery( "SELECT * FROM table_name" );
while (resultSet.next()) {
String name = resultSet.getString( "column_name" );
int age = resultSet.getInt( "column_name" );
System.out.println(name + " - " + age);
}
resultSet.close();
statement.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
|
Copy after login
In the above code, we generated a database with MySQL The database connection executes a query statement and traverses the query results.
The above is the detailed content of What common classes and methods are used for Java database connections?. For more information, please follow other related articles on the PHP Chinese website!