JDBC連接MYSQL

package org.spring.springboot.controller;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class JDBCTest {
public static void main(String[] args) throws Exception {
Connection connection = null;
PreparedStatement prepareStatement = null;
ResultSet rs = null;

    try {
        // 加載驅動
        Class.forName("com.mysql.jdbc.Driver");
        // 獲取連接
        String url = "jdbc:mysql://127.0.0.1:3306/mytest";
        String user = "root";
        String password = "123456";
        connection = DriverManager.getConnection(url, user, password);
        // 獲取statement,preparedStatement
        String sql = "select * from users where id=?";
        prepareStatement = connection.prepareStatement(sql);
        // 設置參數
        prepareStatement.setLong(1, 1l);
        // 執行查詢
        rs = prepareStatement.executeQuery();
        // 處理結果集
        while (rs.next()) {
            System.out.println(rs.getString("userName"));
            System.out.println(rs.getString("name"));
            System.out.println(rs.getInt("age"));
            System.out.println(rs.getDate("birthday"));
        }
    } finally {
        // 關閉連接,釋放資源
        if (rs != null) {
            rs.close();
        }
        if (prepareStatement != null) {
            prepareStatement.close();
        }
        if (connection != null) {
            connection.close();
        }
    }
}

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章