0
点赞
收藏
分享

微信扫一扫

我的第一个JDBC程序

婉殇成长笔记 2022-04-13 阅读 101

我的第一个JDBC程序

//我的第一个jdbc程序
public class jdbcFirst {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        //===========================1.加载驱动=============================
        
        Class.forName("com.mysql.jdbc.Driver");//固定写法

        //===========================2.填写用户信息=========================

        //指定要使用的数据库+(?useUnicode=true&characterEncoding=utf8&useSSL=false)
  		String url = "jdbc:mysql://localhost:3306/jdbcStudy?useUnicode=true&characterEncoding=utf8&useSSL=false";
        String username="root";
        String password="123456";

        //==========================3.连接成功,数据库对象===================

        //连接数据库并获得连接对象
        Connection connection = DriverManager.getConnection(url, username, password);

        //==========================4.执行SQL的对象========================

        //用来执行sql语句
        Statement statement = connection.createStatement();

        //==========================5.通过执行SQL的对象去执行sql================

        //用一个字符串变量保存要执行的sql命令
        String sql="SELECT * FROM `users`";
        ResultSet resultSet = statement.executeQuery(sql);//运行sql语句并将结果集保存到resultSet对象中

        while (resultSet.next()){
            System.out.println("id="+resultSet.getObject("id"));
            System.out.println("name="+resultSet.getObject("name"));
            System.out.println("password="+resultSet.getObject("password"));
            System.out.println("email="+resultSet.getObject("email"));
            System.out.println("birthday="+resultSet.getObject("birthday"));
        }
        
        //==========================6.释放连接============================
        
        resultSet.close();
        statement.close();
        connection.close();
    }
}

DriverManager:

Class.forName("com.mysql.jdbc.Driver");//固定写法,加载驱动
Connection connection = DriverManager.getConnection(url, username, password);
//connection代表数据库
connection.commit();//事务提交
connection.setAutoCommit();//设置事务自动提交
connection.rollback();//事务回滚

URL:

String url = "jdbc:mysql://localhost:3306/jdbcStudy?useUnicode=true&characterEncoding=utf8&useSSL=false";
//语法:jdbc:mysql://主机地址:端口号/数据库名?参数1&参数2&参数3

Statement:执行SQL的对象

statement.executeQuery();//查询操作,返回ResultSet结果集
statement.execute();//执行任何sql语句
statement.executeUpdate();//执行更新,插入,删除的sql语句,返回受影响的行数
statement.executeBatch();//可以同时执行多个sql语句

ResultSet:查询的结果集,封装了所有的查询结果

获得指定的数据类型:

resultSet.getObject();//在不知道列类型的情况下使用
//如果知道列类型就使用指定的类型
resultSet.getInt()
resultSet.getString()
resultSet.getFloat()
resultSet.getDate()
....

遍历,指针

resultSet.next();//移动到下一个数据
resultSet.beforeFirst();//移动到最前面
resultSet.afterLast();//移动到最后面

释放资源:

resultSet.close();
statement.close();
connection.close();
举报

相关推荐

0 条评论