Idea 连接MySQL数据库

📅 2021-03-05 14:49 👁️ 684 💬 0

Idea 连接MySQL数据库

注意:

  • 需要导入jar包,mysql-connector-java-8.0.16.jar
  • mysql8.0及以上 使用的驱动 drive=com.mysql.cj.jdbc.Driver;
  • url="jdbc:mysql://localhost:3306/(设计的数据库名称)?useSSL=false&serverTimezone=Asia/Shanghai"
import java.sql.*;

/**
 * @author xiaoming
 * @create 2021-03-05 12:11
 */

public class MySqlTest {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {

        // MySQL8.0及以上版本使用
        String driver="com.mysql.cj.jdbc.Driver";
        // 连接上自己新建的数据库,设置useSSL=false,设置时区serverTimezone=Asia/Shanghai
        String url="jdbc:mysql://localhost:3306/MySQLTest?useSSL=false&serverTimezone=Asia/Shanghai";
        String user="root";
        String passWord="123456";
        Connection conn=null;
        Statement stmt =null;

        try {
            // 1、加载驱动
            Class.forName(driver);
            // 2、建立连接
            conn = DriverManager.getConnection(url, user, passWord);
            // 3.创建执行语句的对象
            stmt = conn.createStatement();
            String sql="select ID,Name ,Age,Sex FROM MySqlTest.user";
            // 4.执行数据库语句
            ResultSet resultSet = stmt.executeQuery(sql);

            // 5.输出数据
            while (resultSet.next()){
                System.out.print("id"+resultSet.getInt("id"));
                System.out.print("Name"+resultSet.getString("Name"));
                System.out.print("Age"+resultSet.getInt("Age"));
                System.out.print("Sex"+resultSet.getString("Sex"));
                System.out.println();
            }

        } catch (SQLException SE) {
            SE.printStackTrace();
        }finally {

            // 6. 关闭连接
            stmt.close();
            conn.close();

        }
    }
}

结果图:

登录后才能查看或发表评论, 立即 登录
点击右上角即可分享
微信分享提示