第一个JDBC程序

JDBC01测试代码
public class Jdbc01 {
    public static void main(String[] args) throws SQLException {

        //前置工作:在项目下创建一个文件夹4 比如libs
        //将mysql.jar 拷贝到该目录下,点击 add as library 加入到项目中

        //1.注册驱动
        Driver driver = new Driver();//创建driver对象

        //2.得到连接
        //1).jdbc:mysql:// 规定好表示协议,通过jdbc的方式连接mysql
        //2).localhost 主机,可以是ip地址
        //3).3306 表示mysql监听的端口
        //4).jdbc 连接的哪个数据库
        //5).mysql连接本质就是socket连接
        String url = "jdbc:mysql://localhost:3306/jdbc";
        //将用户名和密码放入到properties 对象
        Properties properties = new Properties();
        //user 和 password是规定好的
        properties.setProperty("user","root");//用户
        properties.setProperty("password","root");//密码

        Connection connect = driver.connect(url, properties);



        //3.执行sql
        //String sql = "insert into actor values(null,'刘德华','男','1970-11-11','110')";
        //String sql = "update actor set name='周星驰' where id = 1";
        String sql = "delete from actor where id = 1";
        //执行静态SQL语句,并返回结果对象
        Statement statement = connect.createStatement();
        int rows = statement.executeUpdate(sql);//如果是dml语句 ,返回的就是影响的行数

        System.out.println(rows > 0 ? "成功" : "失败");

        //4.关闭连接资源
        statement.close();
        connect.close();

    }
}

 

posted @ 2022-06-30 10:55  Resign~as  阅读(15)  评论(0编辑  收藏  举报