java(eclipse)和數據庫(mysql)的連接


java和數據之間的連接,我們通常用的數據庫都是mysql,oracle,但是在中小型企業基本上用的都是mysql,使用的oracle公司基本上都是全國或者全球型的企業,用的比較的少。

public void getConnection() {
        Connection con = null;
        Statement stmt = null;
        ResultSet rs = null;
        try {
            // 獲取數據庫驅動名稱(mysql數據庫)
            Class.forName("com.mysql.jdbc.Driver");
            // 進行數據庫連接,dvd是數據庫名稱,root是數據名,123456是數據密碼
            con = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/dvd", "root", "123456");
            // 執行mysql語句
            String sql = "select * from dvd1";
            //實例化預處理Statement對象
            stmt = con.createStatement();
            //執行mysql代碼
            rs = stmt.executeQuery(sql);
            // 處理得到的數據
            while (rs.next()) {
                int id = rs.getInt("id");
                String name = rs.getString("name");
                String state = rs.getString("state");
                String date = rs.getString("date1");
                int count = rs.getInt("count1");
                System.out.println(id + "\t" + name + "\t" + state + "\t"
                        + date + "\t" + count);
            }

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {// 保證 在數據庫和eclipse之間關閉
            // 關閉數據庫
            try {
                rs.close();
                stmt.close();
                con.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

這是在學習中的基本操作,可以把上面的mysql執行提出來,把eclipse和數據放在一個方法中,下次使用的時候就直接調用

public Connection getConnection(){
        try {

            // 裝載JDBC驅動程序
            Class.forName("com.mysql.jdbc.Driver");
            // 連接數據庫
            con = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/zxd_0922", "root", "123456"); // 創建語句對象
        } catch (Exception e) {
            e.printStackTrace();
        }
        return con;
    }

每次調用時,需要接受con數據,

con=m.getConnection();

這是mysql和eclipse連接,第一次寫博客,希望大家多多支持,有錯誤指出,對你有幫助點個贊。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM