淺談如何用MyEclipse連接MySQL
分享MyEclipse連接MySQL經(jīng)驗
我用的MySQL是apmserv的環(huán)境,同時開啟Tomcat和apmserv環(huán)境不會有沖突
需要下載好的東西:MySQL-connector-java-5.0.3-bin.jar
在配置好MyEclipse的JSP基本環(huán)境后
開啟apmserv后,配置MyEclipse的鏈接環(huán)境:window-open perspection-MyEclipse database exp...新建一個鏈接,url處:jdbc:MySQL:(MySQL數(shù)據(jù)庫鏈接),username和password是登錄數(shù)據(jù)庫的(不要弄錯了).在finish前可以嘗試鏈接,鏈接成功-finish.鏈接失敗注意看提示,一般是url的錯誤,多多嘗試.我用apmserv的url是jdbc:MySQL:127.0.0.1/(數(shù)據(jù)庫名)
之后在新建的web工程下,在WEB-INF\lib中improt-general-file system-選擇MySQL-connector-java-5.0.3-bin.jar所在的文件夾-finish
使用下面的代碼,可以測試鏈接,注意更改使用的數(shù)據(jù)庫名,數(shù)據(jù)等
- JDBCHelloWorld.java
- import java.sql.SQLException;
- /**
- * 第一個 JDBC 的 HelloWorld 程序, 數(shù)據(jù)庫訪問 MySQL.
- */
- public class JDBCHelloWorld {
- /**
- * @param args
- * @throws SQLException
- */
- public static void main(String[] args) throws SQLException {
- // 1. 注冊驅動
- try {
- Class.forName("com.MySQL.jdbc.Driver");
- } catch (ClassNotFoundException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }// MySQL 的驅動
- // 2. 獲取數(shù)據(jù)庫的連接
- java.sql.Connection conn = java.sql.DriverManager.getConnection(
- "jdbc:MySQL://localhost/test?useUnicode=true&characterEncoding=GBK", "root", null);
- // 3. 獲取表達式
- java.sql.Statement stmt = conn.createStatement();
- // 4. 執(zhí)行 SQL
- java.sql.ResultSet rs = stmt.executeQuery("select * from user");
- // 5. 顯示結果集里面的數(shù)據(jù)
- while(rs.next()) {
- System.out.println(rs.getInt(1));
- System.out.println(rs.getString("username"));
- System.out.println(rs.getString("password"));
- System.out.println();
- }
- // 6. 釋放資源
- rs.close();
- stmt.close();
- conn.close();
- }
- }
【編輯推薦】