How to carry out database integration for Java function development
The database is an important part of application development and can easily store and manage data. In Java development, data persistence is usually implemented through a database. This article will introduce how to use Java for database integration, including connecting to the database, executing SQL statements, and processing data addition, deletion, modification, and query operations.
import java.sql.*; public class DBConnector { private static final String url = "jdbc:mysql://localhost:3306/test"; private static final String username = "root"; private static final String password = "123456"; public static Connection getConnection() throws SQLException { try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } return DriverManager.getConnection(url, username, password); } public static void main(String[] args) { try { Connection conn = getConnection(); System.out.println("Successful connection to the database!"); } catch (SQLException e) { e.printStackTrace(); } } }
In the above code, we used the MySQL database driver com.mysql.jdbc.Driver and specified the connection URL, user name and password. The getConnection() method returns a Connection object representing the connection to the database.
import java.sql.*; public class DBConnector { // ... public static void main(String[] args) { try { Connection conn = getConnection(); Statement stmt = conn.createStatement(); String sql = "SELECT * FROM users"; ResultSet rs = stmt.executeQuery(sql); while (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("name"); String email = rs.getString("email"); System.out.println("ID: " + id + ", Name: " + name + ", Email: " + email); } } catch (SQLException e) { e.printStackTrace(); } } }
In the above code, we created a Statement object, then executed a query statement SELECT * FROM users, and obtained the query results through the ResultSet object. Next, we traverse the ResultSet object and obtain the data for each row.
import java.sql.*; public class DBConnector { // ... public static void main(String[] args) { try { Connection conn = getConnection(); String sql = "INSERT INTO users (name, email) VALUES (?, ?)"; PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setString(1, "John"); pstmt.setString(2, "john@example.com"); pstmt.executeUpdate(); System.out.println("Data inserted successfully!"); } catch (SQLException e) { e.printStackTrace(); } } }
In the above code, we use the PreparedStatement object, set the parameter value in the SQL statement through the setString() method, and then execute the executeUpdate() method to insert data.
The above is the detailed content of How to perform database integration for Java function development. For more information, please follow other related articles on the PHP Chinese website!