gpt4 book ai didi

java - 用java打印SQL表

转载 作者:行者123 更新时间:2023-12-01 19:21:07 25 4
gpt4 key购买 nike

我无法使用 JAVA 打印 SQL 表。我认为 JDBC Connection 没有问题。如何在控制台中打印表格?

Connection conn = null;
Statement stmt = null;
String url = "jdbc:oracle:thin:@localhost:1521:orcl";
String user = "system";
String pwd = "SSTTaarr00119922";
ResultSet rs = null;

我做了 drivermanager getconnection。

System.out.println("start Connection");
try {
Class.forName("oracle.jdbc.OracleDriver");
conn = DriverManager.getConnection(url, user, pwd);
} catch (ClassNotFoundException e1) {
System.out.println("Error loading driver:" + e1.toString());
return;
} catch (Exception e2) {
System.out.println("Fail DB Connection:" + e2.toString());
return;
}
String sql = "SELECT * FROM dept";
try {
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
System.out.println(sql);
while (rs.next()) {
String deptno = rs.getString(1);
String dname = rs.getString(2);
String Loc = rs.getString(3);

System.out.println(deptno + dname + Loc);

}

我无法在运行时打印。

最佳答案

在您的代码中,您缺少 try---catch block 中的 catch。下面的代码适用于 SQL Server

Connection conn = null;
Statement stmt = null;
ResultSet rs = null;

System.out.println("start Connection");
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn = DriverManager.getConnection("jdbc:sqlserver://localhost;databaseName=xxx;", "yyy", "zzz");
} catch (ClassNotFoundException e1) {
System.out.println("Error loading driver:" + e1.toString());
return;
} catch (Exception e2) {
System.out.println("Fail DB Connection:" + e2.toString());
return;
}

String sql = "SELECT * FROM [dbo].[User]";
try {
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
System.out.println(sql);
while (rs.next()) {
String deptno = rs.getString(1);
String dname = rs.getString(2);
String Loc = rs.getString(3);

System.out.println(deptno + dname + Loc);

}
} catch (Exception e2) {
System.out.println("Fail DB Connection:" + e2.toString());
}

关于java - 用java打印SQL表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59353148/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com