1.首先需要安装MySQL,全部安装,系统会自动安装Connecter J,这是Java连接MySQL的连接器
2.用Intellij Idea新建一个Console项目
3.在File->Project Structure->Project Setting->Libraries,点击加号,选择MySQL安装目录,找到Connecter J,
这个文件通常叫“mysql-connector-java-5.1.39-bin.jar”,其中的版本号会不一样。
4.添加如下代码:
import java.sql.*;
public class Main {
public static void main(String[] args) {
try{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Success loading MySQL Driver");
}
catch(Exception e){
System.out.println("Error loading MySQL Driver!");;
e.printStackTrace();
}
try{
Connection connect = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/world",
"root","123456");
System.out.println("Success connect Mysql Server!");
Statement stmt = connect.createStatement();
ResultSet rs = stmt.executeQuery("select * from city");
while(rs.next()){
System.out.println(rs.getString("Name"));
}
}
catch(Exception e){
System.out.println("get data error!");
e.printStackTrace();
}
}
}