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();
}
}
}
}