Intellij idea 连接mysql数据库

1、下载mysql驱动

需要将mysql driver导入到项目中

方法如下:file->project structure->dependcies(add jar包)

2、连接数据库代码如下

import java.sql.*;
public class JdbcTest {
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    //数据库的名称为 EXAMPLE
    static final String DB_URL = "jdbc:mysql://localhost/EXAMPLE";

    //  数据库用户和密码
    static final String USER = "root";

    static final String PASS = "123";

    public static void main(String[] args) {
        Connection conn = null;
        Statement stmt = null;
        try {

            //注册JDBC 驱动程序
           // Class.forName("com.mysql.jdbc.Driver");
            Class.forName("com.mysql.jdbc.Driver");
            //打开连接
            System.out.println("Connecting to database...");
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/example","root","123");//root,"123"为账号和密码

            //执行查询
            System.out.println("Creating statement...");
            stmt = conn.createStatement();
            String sql;
            sql = "SELECT id, name, name FROM student";
            ResultSet rs = stmt.executeQuery(sql);

            //得到和处理结果集
            while (rs.next()) {
                //检索
               int id=rs.getInt("id");
               String name=rs.getString("name");
               System.out.println(id);
            }
            //清理环境
            rs.close();
            stmt.close();
            conn.close();
        } catch (SQLException se) {
            // JDBC 操作错误
            se.printStackTrace();
        } catch (Exception e) {
            // Class.forName 错误
            e.printStackTrace();
        }

    }
}


你可能感兴趣的:(java)