JDBC的入门(idea,mysql)
JDBC的基本操作:
- 导入驱动.jar包
(1)复制mysql-connector-java-8.0.19.jar到项目libs目录下
(2)右键—>Add As Library - 注册驱动
- 获取数据库的连接对象
- 定义sql语句
- 获取执行sql的对象Statement
- 执行sql
- 处理结果
- 释放资源
JDBC使用代码:
public class jdbc_01 {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//2、注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//获取数据库的连接对象j
Connection con = DriverManager.getConnection
("jdbc:mysql://localhost:3306/bjpowernode","root", "yky");
//定义sql语句
String sql = "update t_class set cname = 'kkkkkkkkkk' where cno = 101";
//获取执行sql的对象Statement
Statement stmt = con.createStatement();
//执行sql
int count = stmt.executeUpdate(sql);
//处理结果
System.out.println(count);
//释放资源
stmt.close();
con.close();
}
}
遇到了错误: Exception in thread “main” java.sql.SQLException
Exception in thread "main" java.sql.SQLException: The server time zone value
'�й���ʱ��' is unrecognized or represents more than one time zone. You must
configure either the server or JDBC driver (via the 'serverTimezone' configuration
property) to use a more specifc time zone value if you want to utilize time zone
support.
报错原因:
- 在使用mysql的jdbc驱动最新版(6.0+)时,遇到数据库和系统时区差异引起的问题。
1、解决方法1-在jdbc url指定默认时区:
还有一种是在jdbc连接的url后面加上serverTimezone=UTC或GMT即可,如果指定使用gmt+8时区,需要写成GMT%2B8,否则可能报解析为空的错误。示例如下:
jdbc.url=jdbc:mysql://localhost:3306/demo?serverTimezone=UTC
2、解决方法2-在数据库配置中添加默认时区,SQL语句配置全局时区
mysql> show variables like '%time_zone%';
+------------------+--------+
| Variable_name | Value |
+------------------+--------+
| system_time_zone | |
| time_zone | SYSTEM |
+------------------+--------+
设置当前session时区,即时生效,但仅作用于当前session
mysql> set time_zone='+8:00';
Query OK, 0 rows affected (0.00 sec)
设置全局时区,即时生效,作用于所有session
mysql> set global time_zone='+8:00';
Query OK, 0 rows affected (0.00 sec)
mysql> show variables like '%time_zone%';
返回结果 1
+------------------+--------+
| Variable_name | Value |
+------------------+--------+
| system_time_zone | |
| time_zone | +08:00 |
+------------------+--------+
2 rows in set, 1 warning (0.00 sec)
原先表格:
+-----+-----------------------------+
| cno | cname |
+-----+-----------------------------+
| 101 | xxxxxxxxxxxxxxxxxxxxxxxxxxx |
| 102 | yyyyyyyyyyyyyyyyyyyyyyyyyy |
+-----+-----------------------------+
程序运行后::
+-----+----------------------------+
| cno | cname |
+-----+----------------------------+
| 101 | kkkkkkkkkk |
| 102 | yyyyyyyyyyyyyyyyyyyyyyyyyy |
+-----+----------------------------+

浙公网安备 33010602011771号