jdbc1

连接数据库代码

1.加在驱动
2.建立连接
需要url地址
需要用户名username
需要密码password

3.发送sql语句
需要Statement

4.执行返回结果
如果是查询用ResultSet接收
如果是增加修改用int接收
image

连接数据库的代码

package lesson;

import javax.sql.StatementEvent;
import java.sql.*;

/**
 * Created by Administrator on 2022/7/29.
 */
public class JdbcFristDemo {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        //1.加载驱动,需要导入包
        Class.forName("com.mysql.jdbc.Driver");



        String url = "jdbc:mysql://localhost:3306/school?useUnicode=true&characterEncoding=utf8&useSSL=true";
        String username = "root";
        String password = "root";
        //2.获得连接,连接需要url,username,password
        Connection connection = DriverManager.getConnection(url ,username ,password);


        //3.用这个对象发送sql语句
        Statement statement = connection.createStatement();

      String sql = "SELECT * FROM `subject`";

        //4.执行,sql查询后的返回值给ResultSet
        ResultSet resultSet = statement.executeQuery(sql);
        while(resultSet.next()) {
            System.out.println("subjectno=" + resultSet.getObject("subjectno"));
            System.out.println("subjectname=" + resultSet.getObject("subjectname"));
            System.out.println("classhour=" + resultSet.getObject("classhour"));
            System.out.println("gradeid=" + resultSet.getObject("gradeid"));
            System.out.println("===============================");
        }
        resultSet.close();
        statement.close();
        connection.close();

    }
}

posted @ 2022-08-02 16:18  笑到肚子疼  阅读(24)  评论(0)    收藏  举报