Student.java
<span style="font-size:18px;">package com.dqpi.eonline.model;
public class Student {
private int id;
private String name;
private int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
</span>
Session.java
<span style="font-size:18px;">import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.HashMap;
import java.util.Map;
import com.dqpi.eonline.model.Student;
public class Session {
//假设已经读到该表
String tableName = "_student";
Map<String, String> cfs = new HashMap<String, String>();
String[] methodNames;
public Session(){
cfs.put("_id", "id");
cfs.put("_name", "name");
cfs.put("_age", "age");
methodNames = new String[cfs.size()];
}
/**
* 保存Student的对象s
* @param s
*/
public void save(Student s) throws Exception{
String sql = createSql();
//连接数据库
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/hibernate","root","root");
PreparedStatement ps = connection.prepareStatement(sql);
//在ps中设值
for(int i=0;i<methodNames.length;i++){
Method m = s.getClass().getMethod(methodNames[i]);
Class r = m.getReturnType();
if(r.getName().equals("java.lang.String")){
String returnValue = (String) m.invoke(s);
ps.setString(i+1, returnValue);
}
if(r.getName().equals("int")){
Integer returnValue = (Integer) m.invoke(s);
ps.setInt(i+1, returnValue);
}
System.out.println(m.getName() + "|" + r.getName());
}
ps.executeUpdate();
ps.close();
connection.close();
}
/**
* 拼sql语句
* @return
*/
private String createSql() {
String str1 = "";
String str2 = "";
int index = 0;
for(String s:cfs.keySet()){
String v = cfs.get(s);
v = Character.toUpperCase(v.charAt(0)) + v.substring(1);
methodNames[index] = "get" + v;
str1 += s + ",";
index++;
}
str1 = str1.substring(0, str1.length()-1);
System.out.println(str1);
for(int i=0;i<cfs.size();i++){
str2 += "?,";
}
str2 = str2.substring(0, str2.length()-1);
System.out.println(str2);
String sql = "insert into " + " tableName " + "(" + str1 + ")" + " values " + "(" + str2 + ")";
System.out.println(sql);
return sql;
}
}
</span>
StudentTest.java
<span style="font-size:18px;">import com.dqpi.eonline.model.Student;
/**
* 驱动测试
* @author Administrator
*
*/
public class StudentTest {
public static void main(String[] args) throws Exception {
Student s = new Student();
s.setId(111);
s.setName("aaa");
s.setAge(20);
Session session = new Session();
session.save(s);
}
}
</span>