<?php$servername = "localhost";$username = "username";$password = "password";$dbname = "database_name";$conn = new mysqli($servername, $username, $password, $dbname);if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error);}$sql = "SELECT * FROM table_name";$result = $conn->query($sql);if ($result->num_rows > 0) { while($row = $result->fetch_assoc()) { echo $row["column_name"]. "<br>"; }} else { echo "0 results";}$conn->close();?> 将这段代码更换为java
时间: 2024-01-11 15:02:43 浏览: 105
PHP中mysqli_get_server_version()的实例用法
这段代码是使用PHP语言编写的,如果想要将其转换为Java版本,需要进行如下步骤:
1. 连接数据库
PHP使用mysqli扩展提供MySQL数据库连接功能,而Java可以使用JDBC(Java Database Connectivity)来连接MySQL数据库。
在Java中,需要导入MySQL的JDBC驱动包,然后使用以下代码连接数据库:
```
import java.sql.*;
public class Main {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/database_name";
String username = "username";
String password = "password";
try {
Connection conn = DriverManager.getConnection(url, username, password);
System.out.println("Connected to the database");
// 其他操作
conn.close();
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
}
```
2. 执行SQL查询
在Java中,可以使用Statement或PreparedStatement对象执行SQL查询语句,与PHP中的mysqli_query()函数类似。
例如,将原来的SQL查询代码转换为Java代码如下:
```
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM table_name");
if (rs.next()) {
do {
System.out.println(rs.getString("column_name"));
} while (rs.next());
} else {
System.out.println("0 results");
}
```
完整的Java代码如下:
```
import java.sql.*;
public class Main {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/database_name";
String username = "username";
String password = "password";
try {
Connection conn = DriverManager.getConnection(url, username, password);
System.out.println("Connected to the database");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM table_name");
if (rs.next()) {
do {
System.out.println(rs.getString("column_name"));
} while (rs.next());
} else {
System.out.println("0 results");
}
conn.close();
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
}
```
阅读全文