1. 程式人生 > >eclipse開發工具動態網站專案使用jdbc連線資料庫

eclipse開發工具動態網站專案使用jdbc連線資料庫

首先,要到這裡https://dev.mysql.com/downloads/connector/j/5.0.html下載mysql-connector-java的壓縮檔案。

然後,解壓縮,將資料夾下的mysql-connector-java-xxx-bin.jar檔案複製到webContent的lib目錄下。這樣,就可以在jsp中使用jdbc連線資料庫了。在java recesources目錄下添加了庫之後,用jsp連線還是有錯,在網上查了資料,要將jar放在WEB-INF/lib資料夾下。

連線程式碼(只放了Jsp中對連線有用的部分):


<%@ page language="java" import="java.sql.*" %>

<body>
<%
Connection connect = null;
Statement statement = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
    // This will load the MySQL driver, each DB has its own driver
    Class.forName("com.mysql.jdbc.Driver");
    // Setup the connection with the DB
    connect = DriverManager.getConnection("jdbc:mysql://" + "localhost" + "/yourdatabasename?"+ "user=" + "yourusername" + "&password=" + "yourpassword" );
    statement=connect.createStatement();
    resultSet=statement.executeQuery("select title from databasename.tablename");
   while(resultSet.next()){
%>
<%= resultSet.getString("title") %>
<br>
<% 
}
   %>
</body>

粘上來就這麼簡單,可我妥妥地被虐了將近三個小時。轉載請說明出處

誰讓我用java的時候從來不連資料庫。。。。。。。。