使用idea操作数据库
我们点击左上角视图,工具窗口中的database
然后点击左上角加号
依次进入data source -> mysql
依次填写用户和密码
然后点击连接,第一次连接可能会报错如图
这是因为我们数据库没有设置时区
设置时区:
先win+r cmd
连接数据库,输入mysql -hlocalhost -uroot -p 并输入密码
连接成功后
输入show variables like'%time_zone'; 显示当前时区配置
如果你的value栏显示的是SYSTEM ,则没有设置时区,我的是设置好了的
输入set global time_zone = '+8:00';回车 即可设置时区
再次输入show variables like'%time_zone';确认设置成功
即可
回到idea 点击test connection进行测试
显示如图即测试成功,点击确认进行连接
之后便可在idea内输入sql语句操作数据库
使用jdbc操作mysql环境配置:
首先我们项目下新建一个lib,然后把驱动放进去
没有驱动的可以到mysql驱动官网下载对应自己版本的mysql驱动
系统选择platform independent,然后window系统下载zip即可
把驱动拖入lib文件夹
右键lib 选择添加为库(add as library)
之后点开驱动,看到以下文件即成功
现在驱动安装好了
这是用来演示操作的数据库
src中 jdbc代码如下
package com.lxr.conn;
import java.sql.*;
public class books{
public static void main(String[] args) {
Connection connection = null;
Statement statement = null;
ResultSet result = null;
try {
//1. 加载驱动 这步大家应该差不多
Class.forName("com.mysql.cj.jdbc.Driver");
//2. 提供数据库连接的信息和账号密码
//test01 为你要操作表所在的数据库
String url = "jdbc:mysql://localhost:3306/test01";
String username = "root";
String password = "13154511118liu";
//3. 连接数据库
connection = DriverManager.getConnection(url, username, password);
//4. 创建执行 sql 的对象
statement = connection.createStatement();
//5. 执行 SQL、获取返回结果并查看
String sql = "SELECT `name`,`authors`,`price`,`pubdate`,`num` FROM books";
result = statement.executeQuery(sql);
while (result.next()) {
System.err.println("name=" + result.getString("name"));
System.err.println("authors=" + result.getString("authors"));
System.err.println("price=" + result.getInt("price"));
System.err.println("pubdate=" + result.getInt("pubdate"));
System.err.println("num=" + result.getInt("num"));
System.err.println("======================");
}
} catch (Exception e) {
System.err.println(e.getMessage());
} finally {
//6. 释放连接
try {
result.close();
statement.close();
connection.close();
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}
}
运行
查找成功
总体项目结构如下