java 簡單的控制台程式實現mysql資料讀取

來源:互聯網
上載者:User

標籤:

建立控制台應用程式Application client project

 

引入jar包

import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;

 

引入mysql串連就jar包

項目  properties—>build path –> add  extend jar

mysql-connector-java-5.1.38-bin.jar

Connection connection = null;        // 先行編譯的Statement,使用先行編譯的Statement提高資料庫效能        PreparedStatement preparedStatement = null;        // 結果 集        ResultSet resultSet = null;        try {            // 載入資料庫驅動            Class.forName("com.mysql.jdbc.Driver");            // 通過驅動管理類擷取資料庫連結            connection = DriverManager                    .getConnection(                            "jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8",                            "root", "123456");            // 定義sql語句 ?表示預留位置            String sql = "select * from users where name = ?";            // 擷取預先處理statement            preparedStatement = connection.prepareStatement(sql);            // 設定參數,第一個參數為sql語句中參數的序號(從1開始),第二個參數為設定的參數值            preparedStatement.setString(1, "使用者孤傲蒼狼");            // 向資料庫發出sql執行查詢,查詢出結果集            resultSet = preparedStatement.executeQuery();            // 遍曆查詢結果集            while (resultSet.next()) {                System.out.println(resultSet.getString("id") + "  "                        + resultSet.getString("name"));            }        } catch (Exception e) {            e.printStackTrace();        } finally {            // 釋放資源            if (resultSet != null) {                try {                    resultSet.close();                } catch (SQLException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                }            }            if (preparedStatement != null) {                try {                    preparedStatement.close();                } catch (SQLException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                }            }            if (connection != null) {                try {                    connection.close();                } catch (SQLException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                }            }        }

java 簡單的控制台程式實現mysql資料讀取

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.