连接前的三个条件:下载好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();}}
}
创建的表
运行连接数据库输出内容