jdbc小demo

package top.enjoy.test.jdbc;


import java.sql.*;
import java.util.List;


public class Demo1 {
    public static void main(String[] args) throws Exception {

        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            //加載數據庫驅動
            Class.forName("com.mysql.cj.jdbc.Driver");

            //通過驅動管理獲取數據庫連接
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/demo?characterEncoding=utf-8","root","root");

            //定義sql
            String sql="select * from stu";

            //建立Statement對象
            PreparedStatement preparedStatement1 = connection.prepareStatement(sql);

            //向數據庫打出sql執行查詢 ,查詢出結果集
            resultSet = preparedStatement1.executeQuery();

            //遍歷查詢結果
            while (resultSet.next()){
                System.out.printf("id:"+resultSet.getString("id")+" 姓名:"+resultSet.getString("name")+" 年齡:"+resultSet.getString("age"));

            }
        }catch (ClassNotFoundException e){
            e.printStackTrace();
        }finally {
            //釋放資源
            if (resultSet != null){
                try {
                    resultSet.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            ///------------------------
            if (preparedStatement != null){
                try {
                    preparedStatement.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            ///-------------------------
            if (connection != null){
                try {
                    connection.close();
                }catch (SQLException e){
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }


        }


    }
}

後面別忘了引jar包

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