一创建数据库
数据库名studentdb , 表名stable
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for stable
-- ----------------------------
DROP TABLE IF EXISTS `stable`;
CREATE TABLE `stable` (
`sno` int(11) NOT NULL,
`sname` varchar(255) DEFAULT NULL,
`sex` varchar(255) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
PRIMARY KEY (`sno`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of stable
-- ----------------------------
INSERT INTO `stable` VALUES ('1', '1', '1', '1');
INSERT INTO `stable` VALUES ('2', '2', '2', '2');
二 代码
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
/**
* @program: Dorm
* @description:
* @author: Bruse Queen
* @create: 2018-04-13 10:49
**/
public class stuInfo {
private int sno;
private String sname;
private String sex;
private int age;
public int getSno() {
return sno;
}
public void setSno(int sno) {
this.sno = sno;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public stuInfo() {
}
public stuInfo(int sno, String sname, String sex, int age) {
this.sno = sno;
this.sname = sname;
this.sex = sex;
this.age = age;
}
public static void main(String[] args) {
ArrayList<stuInfo> list = getAllStus();
if (list.size() == 0) {
System.out.println("暂无数据");
} else {
for (stuInfo s : list) { //遍历集合数据
System.out.println(s.getSno() + "\t" + s.getSname() + "\t" + s.getSex() + "\t" + s.getAge());
}
}
}
//采用集合的方法,返回数据集合
public static ArrayList<stuInfo> getAllStus() {
ArrayList<stuInfo> stulist = new ArrayList<stuInfo>();
String url = "com.mysql.jdbc.Driver"; //加载驱动包
String connectSql = "jdbc:mysql://127.0.0.1:3306/studentdb"; //链接MySQL数据库
String sqlUser = "root"; //数据库账号
String sqlPasswd = "root"; //你的数据库密码
Connection con = null;
PreparedStatement psm = null;
ResultSet rs = null;
try {
//加载驱动包
Class.forName(url);
//连接MYSQL
con = DriverManager.getConnection(connectSql, sqlUser, sqlPasswd);
//执行MYSQL语句
psm = con.prepareStatement("select * from stable");
rs = psm.executeQuery();
System.out.println("编号" + "\t" + "姓名" + "\t" + "性别" + "\t" + "年龄");
while (rs.next()) {
stuInfo s = new stuInfo();
s.setSno(rs.getInt(1));
s.setSname(rs.getString(2));
s.setSex(rs.getString(3));
s.setAge(rs.getInt(4));
stulist.add(s);
}
//关闭数据库连接
rs.close();
psm.close();
con.close();
} catch (Exception e) {
System.out.println("显示所有数据报错,原因:" + e.getMessage());
}
return stulist;
}
}