利用jsp mysql 對數據庫進行訪問

若想做好這個請先到eclpise官網選擇適合自己電腦的版本,下載後選擇安裝javaee(記得先配置好jdk)
再去tomcat下載一個tomcat安裝包,是win10的記得下載tomcat7.0
還要去下載 MYSQL ,安裝的時候要選擇 Only server 不然會安裝很多。(如果要界面的化去下 navicat for mysql)


以上做完之後創建一個動態web項目,在lib目錄下放你下載好的驅動包

<%
Connection conn = null;
Statement stmt;
//加載數據庫驅動類
Class.forName("com.mysql.jdbc.Driver").newInstance();
//數據庫連接URL
String url="jdbc:mysql://127.0.0.1:3306/ysp";//我本地數據庫的名稱叫做ysp;
//數據庫用戶名和密碼
String user="root";//我mysql的賬號和密碼
String password="root";
//根據數據庫參數取得一個數據庫連接值
conn = DriverManager.getConnection(url,user,password);
out.print("取得一個數據庫連接:");
out.print(conn.toString()+"<br/>");
stmt=conn.createStatement();
String sql="select * from Table1";
//以上爲JSP連接數據庫

ResultSet rs=stmt.executeQuery(sql);//返回結果
while (rs.next()) {
int id=rs.getInt("id");
String username=rs.getString("username");
String pwd=rs.getString("pwd");
out.print(id +"號"+" ");
out.print("姓名 : "+ username +"密碼 :"+pwd);

out.print("<a href=\"http://localhost:8080/trttocatch/del.jsp?keyword="+id+"\">刪除</a> &nbsp &nbsp<a href=\"http://localhost:8080/trttocatch/update.jsp?id="+id+"&username="+username+"&password="+pwd+"\">修改</a>"+"<br/>");
}
//以上爲將查詢的結果通過顯示出來
rs.close();
conn.close();
%>

在做東西過程的小錯誤:
在post過程中最好利用 \" 防止 “ 發揮作用。(轉義字符)
另外在操作數據庫中查詢 ResultSet rs=stmt.executeQuery(sql); 改查刪用stmt.executeUpdate(sql);
操作mysql需要有個驅動包
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章