通過Java代碼實(shí)現(xiàn)對數(shù)據(jù)庫的數(shù)據(jù)進(jìn)行添加操作
String names = Tools.isoToUtf8(request.getParameter("names"));
String sex = Tools.isoToUtf8(request.getParameter("sex")) ;
String blood = Tools.isoToUtf8(request.getParameter("blood"));
String hobby = Tools.arrToString(request.getParameterValues("hobby"),',');
String intro = Tools.isoToUtf8(request.getParameter("intro"));
long time = System.currentTimeMillis();
//得到上傳文件名
String pic = UploadFile.getFileName(request,"pic");
//得到上傳文件結(jié)束
//連接數(shù)據(jù)庫開始
try {
Class.forName("com.mysql.jdbc.Driver");//加載驅(qū)動
//用法見:http://www.tjegd.cn/news/show/666.html
String jdbc="jdbc:mysql://127.0.0.1:3306/stu_info";
Connection conn = DriverManager.getConnection(jdbc, "root", "root");//鏈接到數(shù)據(jù)庫
//方法一:
/* Statement state = conn.createStatement(); //state用來執(zhí)行sql語句
String sql = "insert into students" +
" (names, sex, blood, hobby, pic, intro, time)values('"
+ names+"','"+sex + "','" + blood + "','" + hobby + "','" + pic + "','" + intro +"','"+time +"')";
System.out.println(sql);
int count = state.executeUpdate(sql); //將sql語句上傳至數(shù)據(jù)庫執(zhí)行*/
//方法二:
String sql = "insert into students (names,sex,blood,hobby,pic,intro,time) value (?,?,?,?,?,?,?)";
PreparedStatement ps = conn.prepareStatement(sql);
//prepareStatement對象防止sql注入的方式是把用戶非法輸入的單引號用\反斜杠做了轉(zhuǎn)義,從而達(dá)到了防止sql注入的目的
//setObject()用法,其中,第一個(gè)是指你SQL語句中的第幾個(gè)參數(shù),第二個(gè)是要設(shè)置的值
ps.setObject(1,names);
ps.setObject(2,sex);
ps.setObject(3,blood);
ps.setObject(4,hobby);
ps.setObject(5,pic);
ps.setObject(6,intro);
ps.setObject(7,time);
int count = ps.executeUpdate();
out.print("添加成功" + count);
ps.close();
conn.close();
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}