javaw3d1-jdbc练习

练习

1.插入一条新数据

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;


public class Demo1 {
    public static void main(String[] args) {
        Connection conn=null;
        Statement statement=null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn= DriverManager.getConnection("jdbc:mysql://localhost:3306/java","root","123");
            String sql="INSERT INTO db1 VALUES(3,'cas',81) ";
            statement=conn.createStatement();
            int count=statement.executeUpdate(sql);
            System.out.println(count);
            statement.close();
            conn.close();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        finally {
            if(statement!=null){
                try {
                    statement.close();

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

                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}

2.删除

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;


public class Demo1 {
    public static void main(String[] args) {
        Connection conn=null;
        Statement statement=null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn= DriverManager.getConnection("jdbc:mysql://localhost:3306/java","root","123");
            String sql="DELETE FROM db1  WHERE id=3 ";
            statement=conn.createStatement();
            int count=statement.executeUpdate(sql);
            System.out.println(count);
            statement.close();
            conn.close();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        finally {
            if(statement!=null){
                try {
                    statement.close();

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

                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}

你可能感兴趣的:(javaw3d1-jdbc练习)