通过JDBC接口连接到MySQL数据库的两种方法

1 通过创建Driver接口,调用实例connect()方法来连接到数据库

import java.sql.SQLException;
import java.util.Properties;
import java.sql.*;
import com.mysql.jdbc.Driver;
public class Demo2 {

    public static void main(String[] args) throws SQLException {
        // TODO Auto-generated method stub
        //创建一个MySQL数据库的驱动
        Driver driver = new Driver();
        //设置要连接到的数据库的信息
        String url = "jdbc:mysql://localhost:3306/test";
        Properties info = new Properties();
        info.setProperty("user", "root");
        info.setProperty("password", "s13562835851w");
        //调用驱动的connect方法建立连接
        Connection connection = driver.connect(url,info);

        System .out.println("连接数据库成功 !!!"+connection );
    }

}

2 加载DriverManager,通过驱动管理器getConnection()方法建立连接

import java.sql.Connection;
import java.sql.DriverManager;

public class Demo1 {

    public static String className = "com.mysql.jdbc.Driver";

    public static void main(String[] args) {
        try {
            //加载MYSQL JDBC驱动程序 
            Class.forName("com.mysql.jdbc.Driver");  
            System.out.println("Success loading Mysql Driver!");

        }catch (Exception e) 
        {  
            System.out.print("Error loading Mysql Driver!");  
            e.printStackTrace();  
        }  

        try{ 
            //连接URL为 jdbc:mysql//服务器地址/数据库名 ,后面的2个参数分别是登陆用户名和密码
            String url = "jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=true";
            String username = "root";
            String password = "s13562835851w";
            //通过驱动管理器获得连接
            Connection connection = DriverManager.getConnection(url,username,password);           
            System.out.println("Success connect Mysql server!!!\n"+connection);  
        }catch(Exception e) 
        {  
             System.out.print("get data error!");  
             e.printStackTrace();  
        }  
    }

}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值