栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

JAVA连接数据库的两种方法

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JAVA连接数据库的两种方法

package First;

import com.mysql.jdbc.Driver;
import org.junit.Test;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;


方式一是静态加载依赖性比较强不推荐使用
public class JDBC_01 {
    public static void main(String[] args) throws SQLException {

 
    //方式1:静态加载
    @Test
    public void method_01() throws SQLException {
        //前置工作:在项目下创建文件夹,将mysql jar文件拷贝过来在add as Library 后加入项目中
        //1,注册驱动
        Driver driver = new Driver();//创建driver对象

        //2,得到连接
        String url = "jdbc:mysql://localhost:3306/firsttry?useSSL=false";
        Properties properties = new Properties();
        properties.setProperty("user","root");//用户
        properties.setProperty("password","zty");//密码
        //获取连接
        Connection connect = driver.connect(url, properties);

        //3,执行sql
        String sql = "insert into onetable values('10','JDBCsql','2000')";
        Statement statement = connect.createStatement();//用于执行静态sql语句并返回生成的结果的对象
        int rows = statement.executeUpdate(sql);//如果是dml语句,返回的就是影响的行数
        System.out.println(rows);
        //4,关闭连接资源
        statement.close();
        connect.close();
    }

方式二是动态加载依赖性不强,可以单独写到properties文件里,方便开发者修改,推荐使用

//方式2:动态加载
@Test
public void method_02() throws ClassNotFoundException, IllegalAccessException, InstantiationException, SQLException {
    //注册驱动
    Class aClass = Class.forName("com.mysql.jdbc.Driver");
    Driver driver = (Driver)aClass.newInstance();
    //获取连接
    String url ="jdbc:mysql://localhost:3306/firsttry?useSSL=false";
    Properties properties = new Properties();
    properties.setProperty("user","root");
    properties.setProperty("password","zty");
    Connection connect = driver.connect(url, properties);
    //执行Mysql
    String sql = "insert into onetable values('20','JDBCsql','2000')";
    Statement statement = connect.createStatement();//用于执行静态sql语句并返回生成的结果的对象
    int rows = statement.executeUpdate(sql);//如果是dml语句,返回的就是影响的行数
    System.out.println(rows);
    //4,关闭连接资源
    statement.close();
    connect.close();
}
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/847446.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号