2015-10-18 103 views
0

我想連接到Java Servlet中的數據庫,但我無法連接。我搜索谷歌和每個網站顯示不同的方式,我不知道爲什麼。在Java Servlet中的數據庫連接

這裏是我嘗試連接的代碼,但沒有任何(數據)會進入MySQL數據庫行。

public class DBConnection{ 
    private static final long serialVersionUID = 1L; 

    private final Connection connection; 
    private final String dbURL = "jdbc:mysql://localhost:3306/Servlet"; 
    private final String user = "root"; 
    private final String pwd = ""; 
    public DBConnection() throws ClassNotFoundException, SQLException{ 
     Class.forName("com.mysql.jdbc.Driver"); 
     this.connection = DriverManager.getConnection(dbURL, user, pwd); 
    } 

    public Connection gC(){ 
     return this.connection; 
    } 
} 

這是我試圖在數據庫中插入數據(但數據沒有添加到數據庫)。

public class ReServlet extends HttpServlet { 
    private static final long serialVersionUID = 1L; 
    @Override 
    protected void doPost(HttpServletRequest req, HttpServletResponse res) 
      throws ServletException, IOException { 
     try{ 
      String uName=req.getParameter("uName"); 
      String uEmail=req.getParameter("uEmail"); 
      String uPass=req.getParameter("uPass"); 
      DBConnection conn=new DBConnection(); 
      PreparedStatement ps; 
      ps = conn.gC().prepareStatement("insert into users(name,email,password) values (?,?,?)"); 
      ps.setString(1, uName); 
      ps.setString(2, uEmail); 
      ps.setString(3, uPass); 
      ps.execute(); 
     }catch(SQLException | ClassNotFoundException se){ 
      se.printStackTrace(); 

     }finally{ 
     } 
    } 
} 

我還要求所有,請給我簡單和容易的數據庫連接例如,關於每個網站顯示的正式註冊或任何其他系統。但我只想簡單的數據庫連接示例,因爲我正在嘗試在我的代碼中。

編輯 通過更換se.printStackTrace();這個throw new RuntimeException(se);我得到這個異常java.lang.RuntimeException: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver

+0

爲什麼'DBConection'擴展'HTTPServlet'?你有什麼異常? – Jens

+0

@Jens對不起,我正在嘗試不同的方式,忘記刪除它。我在哪裏可以看到異常?在編譯時沒有任何東西。 – UnKnown

+1

您可以在服務器的日誌文件中看到 – Jens

回答

-1

您NEDD與DriverManager的註冊你的驅動程序是這樣的:

Class c = Class.forName("com.mysql.jdbc.Driver"); 
    DriverManager.registerDriver(c.newInstance()); 

請記得關閉您的連接最後阻止。

+0

我認爲它可以解決我的問題,但在哪裏添加這些行? – UnKnown

+0

在您的DBConnection構造函數中。 – k0staa