JDBC实现通用查询
package st_2_1;
import java.sql.*;
public class Conn {
private static final String URL
= "jdbc:mysql://localhost:3306/mydb?"
+ "useUnicode=true&characterEncoding=utf8&"
+ "serverTimezone=Asia/Shanghai&useSSL=false";
private static final String USER = "root";
private static final String PASSWORD = "123456";
static Connection conn = null;
static PreparedStatement ps = null;
static ResultSet rs = null;
public static void init(){
if(conn == null){
try{
Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection(URL, USER, PASSWORD);
}catch (Exception e){
System.out.println("Database connection fail");
e.printStackTrace();
}
System.out.println("Database connection success");
}else {
System.out.println("already build database connection");
}
}
public static void query(String sql){
try{
ps = conn.prepareStatement(sql);
rs = ps.executeQuery(sql);
while (rs.next()){
System.out.println(rs.getInt("id") + " " + rs.getString("stu_name"));
}
}catch (SQLException e){
System.out.println("sql query error");
e.printStackTrace();
}
}
public static void update(String sql){
try{
ps = conn.prepareStatement(sql);
int re = ps.executeUpdate();
System.out.println("success, rows affected: " + re);
}catch (SQLException e){
System.out.println("sql modify error");
e.printStackTrace();
}
}
public static void placeholderInsert(String name, int gender){
String sql = "insert into stu_info set stu_name=?, gender=?";
try {
ps = conn.prepareStatement(sql);
ps.setString(1, name);
ps.setInt(2, gender);
System.out.println(ps.execute());
} catch (SQLException e) {
System.out.println("sql run error");
e.printStackTrace();
}
}
public static void batchInsert(String[] sqls){
try{
conn.setAutoCommit(false);
Statement st = conn.createStatement();
for (int i = 0; i < sqls.length; i++){
st.addBatch(sqls[i]);
}
st.executeBatch();
conn.commit();
System.out.println("sql run success");
} catch (SQLException e) {
System.out.println("sql run error");
e.printStackTrace();
}
}
public static void returnPKInsert(String sql){
try{
ps=conn.prepareStatement(sql, ps.RETURN_GENERATED_KEYS);
int re = ps.executeUpdate();
System.out.println("success, rows affected: " + re);
ResultSet rs = ps.getGeneratedKeys();
Integer pk = null;
if(rs.next()){
pk = rs.getInt(1);
}
System.out.println("primary key: " + pk);
} catch (SQLException e) {
System.out.println("sql run error");
e.printStackTrace();
}
}
public static void main(String[] args) {
Conn.init();
query("select * from stu_info");
update("insert into stu_info set id = 15, stu_name='小明'");
placeholderInsert("小李子", 1);
String[] sqls = {
"insert into stu_info set stu_name='刘备'",
"insert into stu_info set stu_name='张飞'",
"insert into stu_info set stu_name='关羽'"
};
batchInsert(sqls);
returnPKInsert("insert into stu_info set stu_name='诸葛孔明'");
}
}
JDBC利用泛型实现通用查询
package st_2_1;
import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class Conn2 {
private static final String URL
= "jdbc:mysql://localhost:3306/mydb?"
+ "useUnicode=true&characterEncoding=utf8&"
+ "serverTimezone=Asia/Shanghai&useSSL=false&allowPublicKeyRetrieval=true";
private static final String USER = "root";
private static final String PASSWORD = "123456";
static Connection conn = null;
static PreparedStatement ps = null;
static ResultSet rs = null;
public static void init(){
if(conn == null){
try{
Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection(URL, USER, PASSWORD);
}catch (Exception e){
System.out.println("Database connection fail");
e.printStackTrace();
}
System.out.println("Database connection success");
}else {
System.out.println("already build database connection");
}
}
public static <T> List<T> queryAll(String sql, Class<T> cla, Object... params){
try{
ps = conn.prepareStatement(sql);
if(params != null){
for(int i = 0; i < params.length; ++i){
ps.setObject(i+1, params[i]);
}
}
rs = ps.executeQuery();
ResultSetMetaData rsd = rs.getMetaData();
List<T> list = new ArrayList<>();
while (rs.next()){
T t = cla.newInstance();
for (int i = 0; i < rsd.getColumnCount(); ++i){
String column = rsd.getColumnLabel(i+1);
Object value = rs.getObject(column);
Field field = cla.getDeclaredField(convertFormat(column));
field.setAccessible(true);
field.set(t, value);
}
list.add(t);
}
return list;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static String convertFormat(String source){
String[] strings = source.split("_");
StringBuffer sf = new StringBuffer(strings[0]);
for(int i = 1; i < strings.length; ++i){
sf.append(strings[i].substring(0,1).toUpperCase() + strings[i].substring(1));
}
return sf.toString();
}
public static void main(String[] args) {
Conn2.init();
String sql = "select * from stu_info where id = ? and stu_name = ?";
List<Student> list = queryAll(sql, Student.class, 14, "小明");
for(Student s: list){
System.out.println(s);
}
}
}
class Student{
private int id;
private String stuName;
private Integer gender;
private Integer claId;
private Integer grade;
@Override
public String toString() {
return "Student{" +
"id=" + id +
", StuName='" + stuName + '\'' +
", gender=" + gender +
", claId=" + claId +
", grade=" + grade +
'}';
}
}