1. 程式人生 > 實用技巧 >JDBC增刪查改

JDBC增刪查改

JDBC

1.jdbc增加資料

public static void main(String[] args) {
        Statement stat=null;
        Connection conn=null;
        try {
            //註冊驅動
            Class.forName("com.mysql.cj.jdbc.Driver");
            //獲取連線物件
            conn= DriverManager.getConnection("jdbc:mysql://localhost:3306/week1?serverTimezone=UTC", "root","root");
            String sql="insert into product values(null,'海飛絲',99,3)";
            //獲取執行SQL語句的物件
            stat = conn.createStatement();
            //執行並獲取返回值
            int count=stat.executeUpdate(sql);
            System.out.println(count);
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        } finally {
            if(stat!=null){
                try {
                    stat.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (conn!=null){
                try{
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

    }

2.jdbc檢視資料

package day01;

import java.sql.*;

public class demo02 {
    public static void main(String[] args) {
        Connection conn=null;
        Statement stat=null;
        ResultSet resultSet=null;
        try{
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn= DriverManager.getConnection("jdbc:mysql://localhost:3306/week1?serverTimezone=UTC",
                    "root","root");
            String sql="select*from product";
            stat=conn.createStatement();
            resultSet=stat.executeQuery(sql);

            while (resultSet.next()){
                int id=resultSet.getInt(1);
                String pname=resultSet.getString(2);
                double salary=resultSet.getDouble(3);
                int cata=resultSet.getInt(4);
                System.out.println("id:"+id+"--pname:"+pname+"--price:"+salary+"--cate:"+cata);
            }
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }finally {
            if(resultSet!=null){
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(stat!=null){
                try {
                    stat.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(conn!=null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}