-
-
-
- import java.lang.reflect.Method;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.PreparedStatement;
- import java.sql.SQLException;
- import java.util.HashMap;
- import java.util.Map;
-
- public class session {
-
- String tableName = "_tableName";
- Map<String, String> cfs = new HashMap<String, String>();
- String[] methedName;
-
- public session() {
-
- cfs.put("_id", "id");
- cfs.put("_name", "name");
- cfs.put("_age", "age");
- methedName=new String[cfs.size()];
-
- }
-
- public void save(student s) throws Exception {
-
- String sql = createSQL();
- Class.forName("com.jdbc.mysql.Driver");
- Connection con=DriverManager.getConnection("jdbc:mysql://localhost/hibernate","lingkai","818927");
- PreparedStatement ps=con.prepareStatement(sql);
-
- for(int i=0;i<methedName.length;i++){
- Method m=s.getClass().getMethod(methedName[i]);
- Class r=m.getReturnType();
-
- if(r.getName().equals("int")){
- Integer returnv=(Integer)m.invoke(s);
- ps.setInt(i+1, returnv);
-
-
-
- }
- if(r.getName().equals("java.lang.String")){
- String returnv=(String)m.invoke(s);
- ps.setString(i+1, returnv);
- }
-
- System.out.println(m.getName()+"|"+m.getReturnType());
-
- }
-
- ps.close();
- con.close();
-
- }
-
- private String createSQL() {
- String str1 = "";
- int index=0;
- for (String s : cfs.keySet()) {
- String v=cfs.get(s);
- v=Character.toUpperCase(v.charAt(0))+v.substring(1);
- methedName[index]="get"+v;
- index++;
- str1 += s + ",";
- }
- str1 = str1.substring(0, str1.length() - 1);
- System.out.println(str1);
- String str2 = "";
- 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 null;
- }
-
- }
-
-
- import java.sql.SQLException;
-
-
- public class test {
-
- public static void main(String[] args) throws Exception {
- student stu=new student();
- stu.setId(1);
- stu.setName("lingkai");
- stu.setAge(21);
-
- session s=new session();
- s.save(stu);
-
-
- }
-
-
-
- }
posted @
2013-06-19 16:21
Breaker-X
阅读(
846)
评论()
编辑
收藏
举报