为啥初始化字符串数组要放在无参构造函数中?放在外面时,就会报数组越界异常?代码如下:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.HashMap;
import java.util.Map;
import com.bdqn.hibernate.model.Student;
public class Session {
//模拟配置文件
String tableName="_Student";
Map cfs=new HashMap();
//定义一个String数组,来存储方法名
String[] methodNames;
public Session() {
cfs.put("_id", "id");
cfs.put("_name", "name");
cfs.put("_age", "age");
methodNames=new String[cfs.size()];
}
public void save(Student s) throws Exception{
//创建sql语句
String sql=createSql();
//加载驱动类
/*Class.forName("com.mysql.jdbc.Driver");
Connection conn=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/hibernate",
"root",
"");
PreparedStatement pst=conn.prepareStatement(sql);
pst.executeUpdate();
pst.close();
conn.close();*/
}
private String createSql() {
String str1="";
//定义变量,用来存储方法名数组的下标
int index=0;
for(String s:cfs.keySet()){
//通过键获取值
String value=cfs.get(s);
//将值的首字母转换成大写
value=Character.toUpperCase(value.charAt(0))+value.substring(1);
//获取方法名
methodNames[index]="get"+value;
System.out.println(methodNames[index]);
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+") value("+str2+")";
System.out.println(sql);
return sql;
}
}