xml
连接到 MySQL 数据库并执行简单的查询。
java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.SQLException;
public class DatabaseConnection {
// 数据库URL
private static final String DB_URL = "jdbc:mysql://localhost:3306/your_database_name";
// 数据库用户名
private static final String USER = "your_username";
// 数据库密码
private static final String PASS = "your_password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
// 注册 JDBC 驱动
Class.forName("com.mysql.cj.jdbc.Driver");
// 打开连接
System.out.println("连接到数据库...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
// 执行查询
System.out.println("创建语句...");
stmt = conn.createStatement();
String sql = "SELECT id, name FROM your_table_name";
ResultSet rs = stmt.executeQuery(sql);
// 展示结果
while (rs.next()) {
// 通过列名获取数据
int id = rs.getInt("id");
String name = rs.getString("name");
// 输出结果
System.out.print("ID: " + id);
System.out.println(", Name: " + name);
}
// 清理环境
rs.close();
stmt.close();
conn.close();
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
// 确保资源被清理
try {
if (stmt != null) stmt.close();
} catch (SQLException se) {
se.printStackTrace();
}
try {
if (conn != null) conn.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
}
}
标签:java,String,stmt,sql,10.16,conn,name From: https://www.cnblogs.com/sword861417845/p/18471094