数据库表格信息用java语言现实到文本区里
时间: 2024-02-29 09:53:01 浏览: 15
您可以使用Java JDBC API连接到数据库并执行SQL语句来查询数据,并将查询结果输出到文本区域中。以下是一个简单的示例代码:
```
import java.sql.*;
import javax.swing.JTextArea;
public class DisplayData {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/your_database_name";
static final String USER = "your_username";
static final String PASS = "your_password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
Class.forName(JDBC_DRIVER);
conn = DriverManager.getConnection(DB_URL,USER,PASS);
stmt = conn.createStatement();
String sql = "SELECT * FROM your_table_name";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
// assuming you have 3 columns in your table
String id = rs.getString("id");
String name = rs.getString("name");
String age = rs.getString("age");
JTextArea textArea = new JTextArea();
textArea.append(id + "\t" + name + "\t" + age + "\n");
}
rs.close();
}catch(SQLException se){
se.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
}
}
```
在上面的代码中,使用JDBC驱动程序连接到MySQL数据库。然后,使用SELECT语句查询指定表的所有数据。每次循环时,获取每一行数据的id、name和age列的值,并将其添加到JTextArea文本区域中。最后,关闭ResultSet和Statement以及数据库连接。您需要将上述代码中的数据库URL、用户名、密码和表名替换为您自己的值。