java连接mysql8的坑

变化:
1.Class.forName(“com.mysql.cj.jdbc.Driver”);
2.conn=DriverManager.getConnection(“jdbc:mysql://localhost/数据库名字?serverTimezone=UTC”,“root”,“密码”);

package chap01;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Jdbc {
	static ResultSet rs;
	static Connection conn;
	static Statement stm;
	public static void main(String[]args) {
		try {
			Class.forName("com.mysql.cj.jdbc.Driver");
			try {
				 conn=DriverManager.getConnection("jdbc:mysql://localhost/stumanage?serverTimezone=UTC","root","123456");
				 System.out.println("连接成功");
				 stm=conn.createStatement();
				String sql="select * from student";
				 rs=stm.executeQuery(sql);
				while(rs.next()) {
					String id=rs.getString("id");
					String name=rs.getString("name");
					String sex=rs.getString("sex");
					 System.out.println(id+name+sex);
				}

			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				System.out.println("连接失败");
			} 
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			try {
				if(rs!=null)
				rs.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try {
				if(stm!=null)
				stm.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try {
				if(conn!=null)
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}
}

有问题评论或留言,
需要源码留邮箱,
多多支持

你可能感兴趣的:(java学习,java,eclipse,mysql8)