最近我在學(xué)習(xí)JSP編程,并且成功地實(shí)現(xiàn)了對(duì)MySQL數(shù)據(jù)庫(kù)的增刪改查操作。接下來(lái),我將與大家分享我是如何實(shí)現(xiàn)這些功能的。
//連接數(shù)據(jù)庫(kù)
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "123456");
//添加數(shù)據(jù)
String sql = "insert into user(name, age) values('Tom', 18)";
stmt = conn.createStatement();
int result = stmt.executeUpdate(sql);
if(result >0){
System.out.println("添加成功!");
}
//刪除數(shù)據(jù)
sql = "delete from user where id=1";
result = stmt.executeUpdate(sql);
if(result >0){
System.out.println("刪除成功!");
}
//修改數(shù)據(jù)
sql = "update user set age=20 where name='Tom'";
result = stmt.executeUpdate(sql);
if(result >0){
System.out.println("修改成功!");
}
//查詢數(shù)據(jù)并輸出
sql = "select * from user";
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
while(rs.next()){
System.out.println(rs.getInt("id") + "," + rs.getString("name") + "," + rs.getInt("age"));
}
通過(guò)這段代碼,我們可以看到JSP操作MySQL數(shù)據(jù)庫(kù)的步驟非常簡(jiǎn)單:連接數(shù)據(jù)庫(kù)、執(zhí)行SQL語(yǔ)句。同時(shí),JSP可以使用Java語(yǔ)言的所有功能,比如循環(huán)、判斷等等,這讓JSP操作MySQL數(shù)據(jù)庫(kù)的方式變得更加靈活。