import java.sql.*;
/**
* @author Vis.Yang
* @project_name
* @date 2021/5/9 13:00
*/
public class ConnectMysql {
public static void main(String[] args) throws SQLException {
//加载驱动
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("加载驱动成功");
} catch (ClassNotFoundException e) {
e.printStackTrace();
System.out.println("加载驱动失败");
}
//定义连接属性
String url="jdbc:mysql://localhost:3306/people?useUnicode=true&characterEncoding=utf8&useSSL=true";
String username="root";
String password="root";
//创建数据库对象
Connection connection = DriverManager.getConnection(url, username, password);
//创建数据库执行sql的对象
Statement statement = connection.createStatement();
//执行sql
String sql="select * from stu_info";
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()){
System.out.println("id="+resultSet.getObject("id"));
System.out.println("stuName="+resultSet.getObject("stuName"));
System.out.println("love="+resultSet.getObject("love"));
}
//关闭资源
resultSet.close();
statement.close();
connection.close();
}
}
mysql8的形式
import java.sql.*;
/**
* @author Vis.Yang
* @project_name
* @date 2021/5/9 13:00
*/
public class ConnectMysql80 {
public static void main(String[] args) throws SQLException {
//加载驱动
try {
Class.forName("com.mysql.cj.jdbc.Driver");
System.out.println("加载驱动成功");
} catch (ClassNotFoundException e) {
e.printStackTrace();
System.out.println("加载驱动失败");
}
//定义连接属性
String url="jdbc:mysql://localhost:3308/student?useUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone=Asia/Shanghai";
String username="root";
String password="root8";
//创建数据库对象
Connection connection = DriverManager.getConnection(url, username, password);
//创建数据库执行sql的对象
Statement statement = connection.createStatement();
//执行sql
String sql="select * from stu_info";
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()){
System.out.println("id="+resultSet.getObject("id"));
System.out.println("stuName="+resultSet.getObject("stuName"));
System.out.println("love="+resultSet.getObject("love"));
}
//关闭资源
resultSet.close();
statement.close();
connection.close();
}
}