連線前的三個條件:下載好JDK環境、Mysql、資料庫驅動jar包
jar包也去MySQL官網上下就可以
然後建立資料庫,我是在Navicat上建的資料庫然後建立的表。也嘗試在小黑框那建立了但總出錯。跟著up主改配置改了一通up主是成果了,我也沒成功。。。、
然後在eclipse上新建專案,連上之前下載好的jar包,打上程式碼,連線
package connect;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class ConnectTest {
private final static String url = "jdbc:mysql://localhost:3306/demo?serverTimezone=GMT";
private final static String username = "root";
private final static String password = "123456";
public static void main(String args[]) {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (Exception e) {
e.printStackTrace();
}
try {
Connection connect = DriverManager.getConnection(url, username, password);
Statement stmt = connect.createStatement();
ResultSet rs = stmt.executeQuery("select * from student");
while (rs.next()) {
System.out.print("id:" + rs.getInt("id")+"\n");
System.out.print("name:" + rs.getString("name")+"\n");
System.out.println("gender:" + rs.getString("gender")+"\n");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
建立的表
執行連線資料庫輸出內容