java中jdbc连接数据库

第一步当然是导入jar包了

第二步

import java.sql.*;

public class Demo001 {
    public static void main(String[] args) {
        try {
            /*数据库地址*/
            String url="jdbc:mysql://localhost:3306/studentdb";
            /*数据库账户*/
            String root="root";
            /*数据库密码*/
            String password="l123456";
            /*加载数据库的驱动*/
            Class.forName("com.mysql.jdbc.Driver");
            /*连接数据库*/
            Connection connection = DriverManager.getConnection(url, root, password);
            /*执行sql语句*/
            PreparedStatement preparedStatement = connection.prepareStatement("select * from student");
           /* 把执行的结果放到集合里面*/
            ResultSet resultSet = preparedStatement.executeQuery();
            /*循环输出*/
            while (resultSet.next()){
                System.out.println(resultSet.getInt(1));
            }

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

  

原文地址:https://www.cnblogs.com/yxs98/p/11293835.html