Java 连接数据库 SQLyog
在连接数据库是我们需要导入几个长见的包
需要的同学自己自行去下载(●’◡’●)我这里就不提供了
步骤(导好包之后)
我们需要创建几个属性负责给SQLyog 的一些基本数据如账号密码类的去登录
//如果SQLyog 的版本在8一下 那么需要把.cj 删除!!!
private static final String DRIVER_CLASS = "com.mysql.cj.jdbc.Driver";
//可以设置你的端口号,不同的可以修改, 必须得指定是使用哪一个数据库 ,还可以设置编码格式 我这里就按我的来设置了
private static final String url = "jdbc:mysql://localhost:3306/task01?characterEncoding=utf8&useSSL=false&serverTimezone=CST";
//设置你的数据库的账号
private static final String username = "root";
//设置你的数据库密码
private static final String password = "root";
设置完上面的之后我们就可以来连接数据库了
public void testConnection(){
Connection connection = null; //设置一个空的连接对象
try {
// 1、加载驱动
Class.forName(DRIVER_CLASS);
// 2、获得连接对象,这里将我们声明的几个属性放进去,需要按顺序来
connection = DriverManager.getConnection(url, username, password);
//返回内存地址,这里如果成功的输出了内存地址说明能正常的连接到数据库。
System.out.println(connection);
//我们需要使用try-catch 这一段。
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally{
// 3、关闭资源,我们需要养成关闭资源的习惯,也需要cty-catch
try {
if(connection!=null)
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
以下就是设置成功的返回地址