jdbc入门 插入语句

package cn.itcast.jdbc;

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

/**
 * @Author: Zhang
 * @Description:
 * @Date: Created in 16:41 2020/12/27
 * @Modified By:
 */
public class JdbcDemo2 {
    
    
    public static void main(String[] args) {
    
    
        Statement statm = null;
        Connection conn = null;
        try {
    
    
            //1.注册驱动
            Class.forName("com.mysql.jdbc.Driver");
            //2.获取数据库连接对象
            conn = DriverManager.getConnection("jdbc:mysql://doitedu01:3306/test", "root", "ABC123abc.123");
            //3.定义需要执行的sql
            String sql = "insert into student values('202001','tom','m','1996','cs','changsha')";
            //4.获取执行sql的对象
            statm = conn.createStatement();
            //5.执行sql
            int count = statm.executeUpdate(sql);
            //6.处理返回结果
            if (count < 0 ){
    
    
                System.out.println("插入失败");
            }else{
    
    
                System.out.println("插入成功");
            }

        } catch (ClassNotFoundException | SQLException e) {
    
    
            e.printStackTrace();
        } finally {
    
    
            //7.释放资源
            //判断是为了避免空指针异常
            if (statm != null){
    
    
                try {
    
    
                    statm.close();
                } catch (SQLException throwables) {
    
    
                    throwables.printStackTrace();
                }
            }

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

        }
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43648241/article/details/111826414