Servlet如何連線MySQL資料庫
publicvoid doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn
"jdbc:mysql://localhost:3306/test", "root", "000000");
stmt = conn.createStatement();
rs = stmt.executeQuery("select * from userinfo");
out.println("<html><head><title>讀取資料庫資訊</title><head><body>");
while (rs.next()) {
out.println(rs.getString(
}
} catch (Exception e) {
e.printStackTrace();
}
}
注意點:
1、仔細檢查連線字串。
2、確認有沒有要操作的這個表。
3、如果出錯了,先去後臺看報錯資訊。
①、message:java.net.connectionException:connection refused:connect-----------
確認MySQL是否啟動。
②、java.lang.classnotfoundexception:om.mysql.jdbc.driver
把驅動拷貝到tomcat下的lib資料夾裡。
有意者加群:108732902