前提准备
首先你要在docker中启动mysql容器,并且暴露3306端口。
中间准备
package delete;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.beans.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Vector;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
public class Stmessege1 extends JFrame {
private static final long serialVersionUID = 1L;
private JTable table;// 声明表格
public Vector getDataVector() throws SQLException, ClassNotFoundException {
Connection conn = null;
java.sql.Statement stmt = null;
Class.forName("com.mysql.jdbc.Driver");
String dburl = "jdbc:mysql://192.168.1.30:3306/mydb";
String dbuser = "root";
String dbpassword = "root";
conn = DriverManager.getConnection(dburl, dbuser, dbpassword);
stmt = conn.createStatement();
String sql = "select* from student";
ResultSet rs = stmt.executeQuery(sql);
Vector dataVector = new Vector();
while(rs.next()) {
Vector rowVector = new Vector();
{
rowVector.add(rs.getString("sno"));
rowVector.add(rs.getString("sname"));
rowVector.add(rs.getString("sex"));
rowVector.add(rs.getString("age"));
}
dataVector.add(rowVector);
}
return dataVector;
}
public Vector getColumnVector() {
Vector columnVector = new Vector();
columnVector.add("sno");
columnVector.add("sname");
columnVector.add("sex");
columnVector.add("age");
return columnVector;
}
public Stmessege1() throws SQLException, ClassNotFoundException {
super();
// setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Connection conn = null;
Statement stmt = null;
Class.forName("com.mysql.jdbc.Driver");
String dburl = "jdbc:mysql://192.168.1.30:3306/mydb";
String dbuser = "root";
String dbpassword = "root";
conn = DriverManager.getConnection(dburl, dbuser, dbpassword);
java.sql.Statement st = conn.createStatement();
String sql = "select* from student";
ResultSet rs = st.executeQuery(sql);
Vector columnVector = getColumnVector();
Vector dataVector = getDataVector();
System.out.println(dataVector.toString());
final JScrollPane scrollPane = new JScrollPane();
getContentPane().add(scrollPane, BorderLayout.CENTER);
table = new JTable(dataVector, columnVector);
table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
table.setFont(new Font("",0,16));
scrollPane.setViewportView(table);
setTitle("连接远程docker数据库显示");
setBounds(100, 100, 382, 223);
setVisible(true);
}
public static void main(String Args[]) throws ClassNotFoundException, SQLException{
new Stmessege1();
}
}