使用JDBC连接Mysql数据库

完全参考菜鸟教程,做了点必要的修改。

package school_databases;

import java.sql.*;
public class ConnectToMysql {
	//JDBC驱动名及数据库URL
	static final String JDBC_DRIVER="com.mysql.cj.jdbc.Driver";
	//需要之命是否使用SSL连接和服务器所在时区
	static final String DB_URL="jdbc:mysql://localhost:3306/university?useSSL=false&serverTimezone=UTC";
	
	//数据库的用户名与密码
	static final String user="root";
	static final String PASS="******";//根据自己数据库用户密码设定
	
	public static void main(String[] args) {
		Connection conn=null;
		Statement stmt=null;
		try {
			//注册JDBC驱动,Mysql8.0以上版本使用
			Class.forName("com.mysql.cj.jdbc.Driver");
			
			//打开链接
			System.out.println("连接数据库...");
			conn=DriverManager.getConnection(DB_URL,user,PASS);
			
			//执行查询
			System.out.println("实例化Statement对象...");
			stmt=conn.createStatement();
			String sql;
			sql="SELECT schoolName,city FROM SCHOOL LIMIT 10";
			ResultSet rs=stmt.executeQuery(sql);
			
			//展开结果集数据库
			while(rs.next()){
				String school=rs.getString("schoolName");
				String city=rs.getString("city");
				
				//输出数据
				System.out.printf("school:%-20s",school);
				System.out.println("city:"+city);
			}
			//完成后关闭
			rs.close();
			stmt.close();
			conn.close();
		}
		catch(SQLException se) {
			//处理JDBC错误????
			se.printStackTrace();
		}catch(Exception e) {
			//处理Class.forName错误
			e.printStackTrace();
		}finally {
			//关闭资源
			try {
				if(stmt!=null) stmt.close();
			}catch(SQLException se2) {
				//什么都不做
			}
			try {
				if(conn!=null) conn.close();
			}catch(SQLException se) {
				se.printStackTrace();
			}
		}
		System.out.println("Goodbye!");
	}
}

猜你喜欢

转载自blog.csdn.net/whimewcm/article/details/83998768