JDBC学习笔记 idea连接MySQL

www.mysql.com->Products->DOWNLOADS->MySQL Connectors->Connector/J->选择合适的版本->download
注.tar是Linux系统用的,windows 下载第二个(.zip)
链接地址:
https://dev.mysql.com/get/Downloads/Connector-J/mysql-connector-java-5.1.47.zip
下载之后解压缩
打开idea点击File选中Project Structure
在这里插入图片描述
Modules->Dependencies->"+"->“1.JARs or directories”
在这里插入图片描述
导入合适的jar包即可。导入成功后左侧会出现依赖关系
在这里插入图片描述
写如下代码,若运行成功则说明连接成功!(打驱动)
import java.sql.*;

 try {
       Class.forName("com.mysql.jdbc.Driver").newInstance();
     }catch (Exception e ){
       e.printStackTrace();
     }

连接好了我们就能查询了

import java.io.FileNotFoundException;
import java.sql.*;

public class Main {
    public static void main(String[] args) {
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost/mydata?user=root&password=root");
            stmt = conn.createStatement();
            rs = stmt.executeQuery("select * from dept");
            while (rs.next()) {
                System.out.println(rs.getString("deptno"));
            }
        } catch (SQLException e) {
            e.getSQLState();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                if (conn != null)
                    conn.close();
                conn = null;
                if (stmt != null)
                    stmt.cancel();
                stmt = null;
                if (rs != null)
                    rs.close();
                rs = null;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_43313769/article/details/85727429
今日推荐