jdbc-MySQL8.0连接

package student;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class main {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//声明Connection对象
String dbURL = “jdbc:mysql://localhost:3306/runoob?useSSL=false&&allowPublicKeyRetrieval=true&&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC”;
String userName = “root”;
String passWord = “123456”;
Class.forName(“com.mysql.cj.jdbc.Driver”);
Connection connection = DriverManager.getConnection(dbURL, userName, passWord);

     Connection con;
     //驱动程序名
     String driver = "com.mysql.cj.jdbc.Driver";
     //遍历查询结果集
     try {
         //加载驱动程序
         Class.forName(driver);            
		//1.getConnection()方法,连接MySQL数据库!!
         con = DriverManager.getConnection(dbURL,userName,passWord);
         if(!con.isClosed())
             System.out.println("Succeeded connecting to the Database!");
         //2.创建statement类对象,用来执行SQL语句!!
         Statement statement = con.createStatement();
         //要执行的SQL语句
         String sql = "select * from websites";
         //3.ResultSet类,用来存放获取的结果集!!
         ResultSet rs = statement.executeQuery(sql);
         System.out.println("--------------------------------------");
         System.out.println("执行结果如下所示:");  
         System.out.println("--------------------------------------");  
         System.out.println("id" + "\t" + "name" + "\t" + "url" + "\t" +"\t"+"country");  
         System.out.println("--------------------------------------");  
         String id = null;
          String name= null;            
         String url = null;
         String country = null;
         while(rs.next()){
        	 //获取sno这列数据
             id = rs.getString("id");
             //获取sname这列数据
             name = rs.getString("name");
             url = rs.getString("url");
             country = rs.getString("country");
             //获取sex这列数据
             //输出结果
             System.out.println(id + "\t" + name+"\t"+url+ "\t" + country);
         }
         rs.close();
         con.close();
     } catch(ClassNotFoundException e) {   
         //数据库驱动类异常处理
         System.out.println("Sorry,can`t find the Driver!");   
         e.printStackTrace();   
         } catch(SQLException e) {
         //数据库连接失败异常处理
         e.printStackTrace();  
         }catch (Exception e) {
         // TODO: handle exception
         e.printStackTrace();
     }
     finally{
         System.out.println("数据库数据成功获取!!");
     }
 }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值