怎么把增删改查封装成一个类,用到时一句话搞定
给你举个小例子:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
public class MySQLDao {
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
static Connection getCon() {
Connection con = null;
try {
con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/cmdp", "root", "123456");
} catch (SQLException e) {
e.printStackTrace();
}
return con;
}
static List<String> get(int id) {
List<String> list = new ArrayList<>();
String sql = "select name from student where id = " + id;
Connection con = getCon();
try {
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
list.add(rs.getString("name"));
}
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
public static void main(String[] args) {
List<String> list = get(3);
for (String str : list) {
System.out.println(str);
}
}
}
根号申 发表于2017-09-18 08:46
给你举个小例子:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
public class MySQLDao {
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
static Connection getCon() {
Connection con = null;
try {
con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/cmdp", "root", "123456");
} catch (SQLException e) {
e.printStackTrace();
}
return con;
}
static List<String> get(int id) {
List<String> list = new ArrayList<>();
String sql = "select name from student where id = " + id;
Connection con = getCon();
try {
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
list.add(rs.getString("name"));
}
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
public static void main(String[] args) {
List<String> list = get(3);
for (String str : list) {
System.out.println(str);
}
}
}
我想把每一行的每一个数据用HashMap保存,然后每一行又装进一个ArrayList
我知道原理但是我不知道怎么做,而且每个数据库列数不尽相同。还有其数据类型,
老师能简单进行指导一下吗?
杨_1492238507 发表于2017-09-18 18:03
我想把每一行的每一个数据用HashMap保存,然后每一行又装进一个ArrayList
我知道原理但是我不知道怎么做,而且每个数据库列数不尽相同。还有其数据类型,
老师能简单进行指导一下吗?
public List get() {
List list = new ArrayList<>();
Map map = new HashMap<>();
Connection con = MySQLDao.getCon();
try {
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from table1 ");
int rowcount = rs.getMetaData().getColumnCount();// 列数
while (rs.next()) {
for (int i = 1; i <= rowcount; i++) {
map.put(rs.getMetaData().getColumnName(i), rs.getString(i));
}
list.add(map);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
MySQLDao.close(con);
}
return list;
}