使用JDBC连接数据库

数据库版本:8.0.12
对应jar包:8.0.12

jar包添加到环境:
使用JDBC连接数据库_第1张图片

创建数据库user
创建数据表:teacher
输入数据
连接代码:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
 
 
public class Database {
     
	public static void main(String []args) {
     
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		 try {
     
	            // The newInstance() call is a work around for some
	            // broken Java implementations
 
	            Class.forName("com.mysql.cj.jdbc.Driver");
	            System.out.println("加载成功");
	        } catch (Exception ex) {
     
	        	System.out.println("加载失败");
	            // handle the error
	        }
		
		try {
     
		    conn =
		       DriverManager.getConnection("jdbc:mysql://localhost/user?serverTimezone=UTC","root","123456");
 
		   System.out.println("连接成功");
		   ps = conn.prepareStatement("select * from teacher;");
		   rs = ps.executeQuery();
		   while(rs.next()) {
     
			   int num = rs.getInt("id");
			   String name = rs.getString("name");
			   System.out.print(num+"\t"+name);
			   System.out.println("");
		   }
		   
 
		   
		} catch (SQLException ex) {
     
		    // handle any errors
		    System.out.println("SQLException: " + ex.getMessage());
		    System.out.println("SQLState: " + ex.getSQLState());
		    System.out.println("VendorError: " + ex.getErrorCode());
		    System.out.println("连接失败");
		}
	}
}

结果显示:
使用JDBC连接数据库_第2张图片

你可能感兴趣的:(笔记)