1.首先需要安裝MySQL肖粮,全部安裝,系統(tǒng)會(huì)自動(dòng)安裝Connecter J目派,這是Java連接MySQL的連接器
2.用Intellij Idea新建一個(gè)Console項(xiàng)目
3.在File->Project Structure->Project Setting->Libraries,點(diǎn)擊加號(hào),選擇MySQL安裝目錄,找到Connecter J箕慧,
這個(gè)文件通常叫“mysql-connector-java-5.1.39-bin.jar”,其中的版本號(hào)會(huì)不一樣。
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();
}
}
}