连接数据库与JDBC的简单操作

连接数据库的步骤没有错,但是mysql--8与jar包--5的版本不匹配导致数据库连接不成功,后面导入8版本的jar包后就连接数据库成功了。
但是报错: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 specific time zone value if you want to utilize time zone support.

需要在将数据库连接对象中的url加上:?serverTimezone=GMT%2B8或者?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8

package com.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBC {
    public static void main(String[]args) throws ClassNotFoundException, SQLException {
        //1、注册驱动
        Class.forName("com.mysql.Driver");

        //2、获取连接
        String url="jdbc:mysql://127.0.0.1:3306/data";
        String username="root";
        String password="Lhw123456";
        Connection conn= DriverManager.getConnection(url,username,password);

        //3、定义sql语句(将表中id为4的对象的upass改为lxy)
        String sql="UPDATE user set upass='lxy' where id='4';";

        //4、获取执行sql的对象
        Statement stmt=conn.createStatement();

        //5、执行sql
        int count=stmt.executeUpdate(sql);

        //6、处理结果
        System.out.println(count);

        //7、释放资源
        stmt.close();
        conn.close();
    }
}


Connection的用法
package com.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBC_Connection {
    public static void main(String[]args) throws ClassNotFoundException, SQLException {
        //1、注册驱动
        Class.forName("com.mysql.cj.jdbc.Driver");


        //2、获取连接
        String url="jdbc:mysql://127.0.0.1:3306/data?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8";
        String username="root";
        String password="Lhw123456";
        Connection conn= DriverManager.getConnection(url,username,password);

        //3、定义sql语句
        String sql1="update account set money=2000 where id=1;";
        String sql2="update account set money=3000 where id=2;";

        //4、获取执行sql的对象
        Statement stmt=conn.createStatement();


        try {
            //开启事务
            conn.setAutoCommit(false);
            //5、执行sql语句
            int count1=stmt.executeUpdate(sql1);

            //6、处理结果
            System.out.println(count1);

            //5.1
            int count2=stmt.executeUpdate(sql2);

            //6.2
            System.out.println(count2);
            //提交事务
            conn.commit();
        } catch (Exception throwables) {
            //回滚事务
            conn.rollback();
            throwables.printStackTrace();
        }

        //7、释放资源
        stmt.close();
        conn.close();
    }
}
posted @ 2024-11-04 17:58  呓语-MSHK  阅读(16)  评论(0)    收藏  举报