JDBC連接數據庫

package jdbc;
import java.sql.*;
public class JdbcDemo{
    public static void JdbcStep(){
        Connection connection  = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try{
            //加載驅動程序
            Class.forName("com.mysql.jdbc.Driver");
            //連接數據庫庫
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/scott?user=root&password=100521&useSSL=true");
            //創建命令
            statement = connection.createStatement();
            //查詢
            resultSet = statement.executeQuery("select deptno,dname from dept");
            //結束處理
            while(resultSet.next()){
                int deptno = resultSet.getInt("deptno");
                String dname = resultSet.getString("dname");
                String row = String.format(
                        "deptno=%d,dname=%s",deptno,dname
                );
                System.out.println(row);
            }
        }catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {

            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    public static void main(String[] args) {
        JdbcStep();
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章