MySql.CLASS
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
public class MySql {
static Connection conn = null;
Statement sta;
ResultSet rs;
String queryna,insertna,insertage,insertsex,insertph;
public Statement getSta() {
String pas, user, url;
pas = "root";
user = "root";
url = "jdbc:mysql://localhost:3306/chj?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC";
try {
conn = DriverManager.getConnection(url, user, pas);
} catch (Exception e) {
System.out.println("error:" + e);
}
try {
sta = conn.createStatement();
} catch (Exception e) {
System.out.println("error:"+e);
}
return sta;
}
public List<String> getQuery() {//把查询的sql数据放到list并返回这个list
List<String> list = new ArrayList<>();
try {
sta = getSta();
rs = sta.executeQuery("select * from anmo");
while (rs.next()) {
String age = rs.getString("age");
String name = rs.getString("name");
String sex = rs.getString("sex");
String phone = rs.getString("phonenum");
list.add(age);
list.add(name);
list.add(sex);
list.add(phone);
}
conn.close();
} catch (Exception g) {
System.out.println("error:" + g);
}
return list;
}
public void insertsql(){//插入方法,暂时没有调用
sta=getSta();
try {
sta.executeUpdate("insert into anmo values ("+insertage+",'"+insertna+"','"+insertsex+"','"+insertph+"')");
conn.close();
}catch (Exception e){
System.out.println("error:" + e);
}
}
}
MyJframe.CLASS
import javax.swing.*;
import java.util.List;
public class MyJFrame extends JFrame {
JPanel jPanel;
JTable jTable;
public MyJFrame(){
this.setTitle("sql list");
this.setBounds(600,200,600,400);
List sqllist=new MySql().getQuery();
int lisize=sqllist.size();//计算list里有多少个数据
String[] col={"年龄","姓名","性别","电话号码"};
String[][] tlist=new String[lisize/4][4];//计算有多少行数据,遍历到二维数组
int li=0;
for (int i = 0; i <lisize/4; i++) {
for (int j = 0; j < 4; j++) {
tlist[i][j]= sqllist.get(li).toString();
li++;
}
}
jPanel=new JPanel();
jTable=new JTable(tlist,col);
jPanel.add(new JScrollPane(jTable));
this.add(jPanel);
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.setVisible(true);
}
}
public class demo {
public static void main(String[] arg){
new MyJFrame();
}
}
运行截图