JAVA连接SQL数据库,并以表格形式输出所有列
时间: 2023-06-05 08:06:13 浏览: 81
好的,我可以回答这个问题。使用JAVA连接SQL数据库需要使用JDBC驱动程序,以下是一个简单的例子:
```java
import java.sql.*;
public class ConnectToDatabase {
public static void main(String args[]) {
try {
// Load the JDBC driver
Class.forName("com.mysql.jdbc.Driver");
// Connect to the database
String url = "jdbc:mysql://localhost/mydatabase";
String username = "root";
String password = "password";
Connection con = DriverManager.getConnection(url, username, password);
// Create a statement
Statement stmt = con.createStatement();
// Execute the query and get the result set
String query = "SELECT * FROM mytable";
ResultSet rs = stmt.executeQuery(query);
// Output the result set as a table
ResultSetMetaData rsmd = rs.getMetaData();
int numColumns = rsmd.getColumnCount();
for (int i = 1; i <= numColumns; i++) {
System.out.print(rsmd.getColumnName(i) + "\t");
}
System.out.println();
while (rs.next()) {
for (int i = 1; i <= numColumns; i++) {
System.out.print(rs.getString(i) + "\t");
}
System.out.println();
}
// Close the result set, statement, and connection
rs.close();
stmt.close();
con.close();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
}
```
这个例子使用了MySQL数据库,你需要将URL、用户名和密码修改为你的数据库信息。执行这个程序会输出所有列。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)