一創(chuàng)建數(shù)據(jù)庫(kù)
數(shù)據(jù)庫(kù)名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("暫無(wú)數(shù)據(jù)");
} else {
for (stuInfo s : list) { //遍歷集合數(shù)據(jù)
System.out.println(s.getSno() + "\t" + s.getSname() + "\t" + s.getSex() + "\t" + s.getAge());
}
}
}
//采用集合的方法谋梭,返回?cái)?shù)據(jù)集合
public static ArrayList<stuInfo> getAllStus() {
ArrayList<stuInfo> stulist = new ArrayList<stuInfo>();
String url = "com.mysql.jdbc.Driver"; //加載驅(qū)動(dòng)包
String connectSql = "jdbc:mysql://127.0.0.1:3306/studentdb"; //鏈接MySQL數(shù)據(jù)庫(kù)
String sqlUser = "root"; //數(shù)據(jù)庫(kù)賬號(hào)
String sqlPasswd = "root"; //你的數(shù)據(jù)庫(kù)密碼
Connection con = null;
PreparedStatement psm = null;
ResultSet rs = null;
try {
//加載驅(qū)動(dòng)包
Class.forName(url);
//連接MYSQL
con = DriverManager.getConnection(connectSql, sqlUser, sqlPasswd);
//執(zhí)行MYSQL語(yǔ)句
psm = con.prepareStatement("select * from stable");
rs = psm.executeQuery();
System.out.println("編號(hào)" + "\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);
}
//關(guān)閉數(shù)據(jù)庫(kù)連接
rs.close();
psm.close();
con.close();
} catch (Exception e) {
System.out.println("顯示所有數(shù)據(jù)報(bào)錯(cuò)信峻,原因:" + e.getMessage());
}
return stulist;
}
}