02使用JDBC连接数据库

步骤1:创建maven工程

步骤2:将MySQL驱动(实际上就是MySQL数据库厂商提供的实现类) 复制到pom.xml中

<!-- 连接MySQL数据库的依赖 -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <!--数据库版本-->
    <version>8.0.15</version>
</dependency>

步骤3:创建一个Demo.java,在其中添加main方法,并添加以下代码

//1. 注册驱动 告诉编译器使用的数据库是什么
Class.forName("com.mysql.cj.jdbc.Driver");
//2. 获取数据库连接 其中3306后的sql为数据库名
Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/sql?
characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&rewrite
BatchedStatements=true","root","root");
System.out.println("连接对象:"+conn);
//3. 创建执行SQL语句的对象  Statement在下方有介绍
Statement s = conn.createStatement();
//4. 执行SQL语句
String sql = "create table jdbct1(id int,name varchar(10))";
s.execute(sql);
System.out.println("创建完成!");
//5. 关闭资源
conn.close();

Statement执行SQL语句的对象

  execute(sql); 可以执行任意SQL语句, 但是推荐执行DDL(数据库相关和表相关的SQL语句)

  executeUpdate(sql); 执行DML(包括增删改查)

  executeQuery(sql); 执行DQL(只包含查询)

 

posted @ 2020-11-15 22:11  print("hello~world")  阅读(100)  评论(0)    收藏  举报