Java项目连入MySQL数据库是一个常见的开发需求,可以通过以下步骤实现:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DatabaseConnector {
public static Connection getConnection() {
Connection connection = null;
String url = "jdbc:mysql://localhost:3306/mydatabase";
String username = "root";
String password = "password";
try {
connection = DriverManager.getConnection(url, username, password);
System.out.println("Database connected successfully!");
} catch (SQLException e) {
System.out.println("Database connection failed.");
e.printStackTrace();
}
return connection;
}
}
在上述示例中,URL是数据库的连接地址,包括主机名、端口号和数据库名称。username和password是连接数据库的用户名和密码。
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class DatabaseOperation {
public static void main(String[] args) {
Connection connection = DatabaseConnector.getConnection();
if (connection != null) {
try {
String sql = "SELECT * FROM users";
PreparedStatement statement = connection.prepareStatement(sql);
ResultSet resultSet = statement.executeQuery();
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
System.out.println("User: " + id + " - " + name);
}
resultSet.close();
statement.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
在上述示例中,通过执行SQL查询语句获取了数据库中的用户数据,并打印输出。
推荐的腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云