【MYSQL】Java的JDBC编程(idea连接数据库)

news2024/9/23 23:31:16

1. 配置

(1)新建一个项目
在这里插入图片描述

(2)Build System 那里选择Maven,下一步Create
在这里插入图片描述
(3)配置pom.xml文件
首先查看自己的MYSQL版本:进入MySQL命令窗口
在这里插入图片描述

我的MYSQL版本是8.0版本的.

下一步,去Maven官网:Maven
点击搜索框,输入Java,回车
在这里插入图片描述
点击下图这个:
在这里插入图片描述
找到对应版本点击进去,比如我的是8.0.28,那我就点即8.0.x最新版的8.0.33。
在这里插入图片描述
下拉,点击Maven,复制里边的代码。
在这里插入图片描述
回到我们刚创建的Java项目,在pom文件中
先写以下代码:

<dependencies>  </dependencies>

再把刚才从Maven中复制的代码放到上面代码的中间。(通常情况会报错,这是正常的):
在这里插入图片描述
(4)setting文件

新建一个setting文件,文件后缀是.xml,然后在文件中填入下面的代码,记住文件路径,记得保存。
在这里插入图片描述

<?xml version="1.0" encoding="UTF-8"?>

<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License.
-->

<!--
 | This is the configuration file for Maven. It can be specified at two levels:
 |
 |  1. User Level. This settings.xml file provides configuration for a single user,
 |                 and is normally provided in ${user.home}/.m2/settings.xml.
 |
 |                 NOTE: This location can be overridden with the CLI option:
 |
 |                 -s /path/to/user/settings.xml
 |
 |  2. Global Level. This settings.xml file provides configuration for all Maven
 |                 users on a machine (assuming they're all using the same Maven
 |                 installation). It's normally provided in
 |                 ${maven.conf}/settings.xml.
 |
 |                 NOTE: This location can be overridden with the CLI option:
 |
 |                 -gs /path/to/global/settings.xml
 |
 | The sections in this sample file are intended to give you a running start at
 | getting the most out of your Maven installation. Where appropriate, the default
 | values (values used when the setting is not specified) are provided.
 |
 |-->
<settings xmlns="http://maven.apache.org/SETTINGS/1.2.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.2.0 https://maven.apache.org/xsd/settings-1.2.0.xsd">
  <!-- localRepository
   | The path to the local repository maven will use to store artifacts.
   |
   | Default: ${user.home}/.m2/repository
  <localRepository>/path/to/local/repo</localRepository>
  -->

  <!-- interactiveMode
   | This will determine whether maven prompts you when it needs input. If set to false,
   | maven will use a sensible default value, perhaps based on some other setting, for
   | the parameter in question.
   |
   | Default: true
  <interactiveMode>true</interactiveMode>
  -->

  <!-- offline
   | Determines whether maven should attempt to connect to the network when executing a build.
   | This will have an effect on artifact downloads, artifact deployment, and others.
   |
   | Default: false
  <offline>false</offline>
  -->

  <!-- pluginGroups
   | This is a list of additional group identifiers that will be searched when resolving plugins by their prefix, i.e.
   | when invoking a command line like "mvn prefix:goal". Maven will automatically add the group identifiers
   | "org.apache.maven.plugins" and "org.codehaus.mojo" if these are not already contained in the list.
   |-->
  <pluginGroups>
    <!-- pluginGroup
     | Specifies a further group identifier to use for plugin lookup.
    <pluginGroup>com.your.plugins</pluginGroup>
    -->
  </pluginGroups>

  <!-- proxies
   | This is a list of proxies which can be used on this machine to connect to the network.
   | Unless otherwise specified (by system property or command-line switch), the first proxy
   | specification in this list marked as active will be used.
   |-->
  <proxies>
    <!-- proxy
     | Specification for one proxy, to be used in connecting to the network.
     |
    <proxy>
      <id>optional</id>
      <active>true</active>
      <protocol>http</protocol>
      <username>proxyuser</username>
      <password>proxypass</password>
      <host>proxy.host.net</host>
      <port>80</port>
      <nonProxyHosts>local.net|some.host.com</nonProxyHosts>
    </proxy>
    -->
  </proxies>

  <!-- servers
   | This is a list of authentication profiles, keyed by the server-id used within the system.
   | Authentication profiles can be used whenever maven must make a connection to a remote server.
   |-->
  <servers>
    <!-- server
     | Specifies the authentication information to use when connecting to a particular server, identified by
     | a unique name within the system (referred to by the 'id' attribute below).
     |
     | NOTE: You should either specify username/password OR privateKey/passphrase, since these pairings are
     |       used together.
     |
    <server>
      <id>deploymentRepo</id>
      <username>repouser</username>
      <password>repopwd</password>
    </server>
    -->

    <!-- Another sample, using keys to authenticate.
    <server>
      <id>siteServer</id>
      <privateKey>/path/to/private/key</privateKey>
      <passphrase>optional; leave empty if not used.</passphrase>
    </server>
    -->
  </servers>

  <!-- mirrors
   | This is a list of mirrors to be used in downloading artifacts from remote repositories.
   |
   | It works like this: a POM may declare a repository to use in resolving certain artifacts.
   | However, this repository may have problems with heavy traffic at times, so people have mirrored
   | it to several places.
   |
   | That repository definition will have a unique id, so we can create a mirror reference for that
   | repository, to be used as an alternate download site. The mirror site will be the preferred
   | server for that repository.
   |-->
  <mirrors>
    <!-- mirror
     | Specifies a repository mirror site to use instead of a given repository. The repository that
     | this mirror serves has an ID that matches the mirrorOf element of this mirror. IDs are used
     | for inheritance and direct lookup purposes, and must be unique across the set of mirrors.
     |
    <mirror>
      <id>mirrorId</id>
      <mirrorOf>repositoryId</mirrorOf>
      <name>Human Readable Name for this Mirror.</name>
      <url>http://my.repository.com/repo/path</url>
    </mirror>
     
     <mirror>
        <id>nexus-aliyun</id>
        <mirrorOf>*</mirrorOf>
        <name>Nexus aliyun</name>
        <url>http://maven.aliyun.com/nexus/content/groups/public</url>
    </mirror> 
    <mirror>
      <id>maven-default-http-blocker</id>
      <mirrorOf>external:http:*</mirrorOf>
      <name>Pseudo repository to mirror external repositories initially using HTTP.</name>
      <url>http://0.0.0.0/</url>
      <blocked>true</blocked>
    </mirror>
    -->
    <mirror>
      <id>aliyun-public</id>
      <mirrorOf>*</mirrorOf>
      <name>aliyun public</name>
      <url>https://maven.aliyun.com/repository/public</url>
    </mirror>
    <mirror>
      <id>aliyun-central</id>
      <mirrorOf>*</mirrorOf>
      <name>aliyun central</name>
      <url>https://maven.aliyun.com/repository/central</url>
    </mirror>
    <mirror>
      <id>aliyun-spring</id>
      <mirrorOf>*</mirrorOf>
      <name>aliyun spring</name>
      <url>https://maven.aliyun.com/repository/spring</url>
    </mirror>
  </mirrors>

  <!-- profiles
   | This is a list of profiles which can be activated in a variety of ways, and which can modify
   | the build process. Profiles provided in the settings.xml are intended to provide local machine-
   | specific paths and repository locations which allow the build to work in the local environment.
   |
   | For example, if you have an integration testing plugin - like cactus - that needs to know where
   | your Tomcat instance is installed, you can provide a variable here such that the variable is
   | dereferenced during the build process to configure the cactus plugin.
   |
   | As noted above, profiles can be activated in a variety of ways. One way - the activeProfiles
   | section of this document (settings.xml) - will be discussed later. Another way essentially
   | relies on the detection of a system property, either matching a particular value for the property,
   | or merely testing its existence. Profiles can also be activated by JDK version prefix, where a
   | value of '1.4' might activate a profile when the build is executed on a JDK version of '1.4.2_07'.
   | Finally, the list of active profiles can be specified directly from the command line.
   |
   | NOTE: For profiles defined in the settings.xml, you are restricted to specifying only artifact
   |       repositories, plugin repositories, and free-form properties to be used as configuration
   |       variables for plugins in the POM.
   |
   |-->
  <profiles>
    <!-- profile
     | Specifies a set of introductions to the build process, to be activated using one or more of the
     | mechanisms described above. For inheritance purposes, and to activate profiles via <activatedProfiles/>
     | or the command line, profiles have to have an ID that is unique.
     |
     | An encouraged best practice for profile identification is to use a consistent naming convention
     | for profiles, such as 'env-dev', 'env-test', 'env-production', 'user-jdcasey', 'user-brett', etc.
     | This will make it more intuitive to understand what the set of introduced profiles is attempting
     | to accomplish, particularly when you only have a list of profile id's for debug.
     |
     | This profile example uses the JDK version to trigger activation, and provides a JDK-specific repo.
    <profile>
      <id>jdk-1.4</id>

      <activation>
        <jdk>1.4</jdk>
      </activation>

      <repositories>
        <repository>
          <id>jdk14</id>
          <name>Repository for JDK 1.4 builds</name>
          <url>http://www.myhost.com/maven/jdk14</url>
          <layout>default</layout>
          <snapshotPolicy>always</snapshotPolicy>
        </repository>
      </repositories>
    </profile>
    -->

    <!--
     | Here is another profile, activated by the system property 'target-env' with a value of 'dev',
     | which provides a specific path to the Tomcat instance. To use this, your plugin configuration
     | might hypothetically look like:
     |
     | ...
     | <plugin>
     |   <groupId>org.myco.myplugins</groupId>
     |   <artifactId>myplugin</artifactId>
     |
     |   <configuration>
     |     <tomcatLocation>${tomcatPath}</tomcatLocation>
     |   </configuration>
     | </plugin>
     | ...
     |
     | NOTE: If you just wanted to inject this configuration whenever someone set 'target-env' to
     |       anything, you could just leave off the <value/> inside the activation-property.
     |
    <profile>
      <id>env-dev</id>

      <activation>
        <property>
          <name>target-env</name>
          <value>dev</value>
        </property>
      </activation>

      <properties>
        <tomcatPath>/path/to/tomcat/instance</tomcatPath>
      </properties>
    </profile>
    -->
  </profiles>

  <!-- activeProfiles
   | List of profiles that are active for all builds.
   |
  <activeProfiles>
    <activeProfile>alwaysActiveProfile</activeProfile>
    <activeProfile>anotherAlwaysActiveProfile</activeProfile>
  </activeProfiles>
  -->
</settings>

按照下图把 User setting file的文件路径改成刚才保存的setting文件路径。
在这里插入图片描述

做完上面的之后,手动点一下下面的图表,重新加载pom(过程可能有点慢)
在这里插入图片描述
最后出现下图的结果配置就完成了。
在这里插入图片描述

2. 连接数据库

2.1 student类

package com.model;

public class Student {
    private int id;
    private String sn;
    private String name;
    private String mail;
    private int classesId;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getSn() {
        return sn;
    }

    public void setSn(String sn) {
        this.sn = sn;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getMail() {
        return mail;
    }

    public void setMail(String mail) {
        this.mail = mail;
    }

    public int getClassesId() {
        return classesId;
    }

    public void setClassesId(int classesId) {
        this.classesId = classesId;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", sn='" + sn + '\'' +
                ", name='" + name + '\'' +
                ", mail='" + mail + '\'' +
                ", classesId=" + classesId +
                '}';
    }
}

2.2 Demo01_Connection类

package com;

import com.model.Student;

import com.mysql.cj.jdbc.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

public class Demo01_Connection {

    // 先定义一个数据源对象
    private static DataSource dataSource = null;
    // 数据库的用户名
    private static final String USER = "root";
    // 数据库的密码
    private static final String PASSWORD = "123456";
    // 数据库连接字符串
    private static final String URL = "jdbc:mysql://127.0.0.1:3306/myjava?characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai";

    public static void main(String[] args) {
        // 1. 初化始数据源
        MysqlDataSource myDataSourse = new MysqlDataSource();
        // 2. 设置连接的参数
        myDataSourse.setURL(URL);
        myDataSourse.setUser(USER);
        myDataSourse.setPassword(PASSWORD);
        // 3. 把构建好的Mysql数据源赋值给JDBC中的datasource
        dataSource = myDataSourse;

        Connection connection = null;
        // 预处理对象
        //Statement statement = null;//危险
        PreparedStatement statement = null;
        ResultSet resultSet = null;

        try{
            // 1. 通过数据源获取一个数据库连接
            connection = dataSource.getConnection();
            // 接收用户输入的值
            System.out.println("请输入学号:");
            Scanner scanner = new Scanner(System.in);
            String sn = scanner.next();
            // 2. 定义SQL语句
//            String sql = "select * from student where sn = '" + sn +"'";//危险操作
            String sql = "select * from student where sn = ?";//?为占位符
            System.out.println(sql);
            // 3. 获取statement对象
//            statement = connection.createStatement();
            // 获取一个预处理对象
            statement = connection.prepareStatement(sql);
            // 处理占位符的值
            statement.setString(1,sn);
            // 4. 执行SQL
            resultSet = statement.executeQuery();
            // 5. 解析结果集,resultSet.next()表示结果集中是否有记录
            if(resultSet.next()){
                // 创建表示结果的JAVA对象
                Student student = new Student();
                // 依次读取结果集中的数据并赋值给JAVA对象
                student.setId(resultSet.getInt(1));
                student.setSn(resultSet.getString(2));
                student.setName(resultSet.getString(3));
                student.setMail(resultSet.getString(4));
                student.setClassesId(resultSet.getInt(5));
                // 打印结果
                System.out.println(student);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            // 依次关闭资源
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}

2.3 测试结果

在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/452628.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【Java基础】Java总览

一、what-什么是Java&#xff1f; Java是一种面向对象的编程语言&#xff0c;其他面向对象的编程语言还有C#&#xff0c;C&#xff0c;Python&#xff0c;Python&#xff0c;golang&#xff0c;VB等。 1、和其他语音对比 对比项\语言CCJava上线时间1972年1979年1995年特点面向…

[pgrx开发postgresql数据库扩展]3.hello world全流程解析

数据库的扩展开发框架 一般来说&#xff0c;数据库的扩展开发主要有的目的就是扩展数据库引擎的能力&#xff08;不管是用pgrx还是其他的框架都一样&#xff09;&#xff1a; 例如PostgreSQL上最著名的扩展PostGIS&#xff0c;就是扩展了PG数据库的空间数据支持能力&#xff…

Linearx配置环境

代码地址 gitssh.dev.azure.com:v3/linearx/PowerDDS/PowerDDS LinearX-5G Wifi pwd: 50186058 Windows报错可以搜索错误代码找官方给出的解决方案 最新版本cmake&#xff1a;ubuntu 20.04安装(升级)cmake - 知乎 (zhihu.com) gtest&#xff1a;gtest的安装_liuzubing的博客…

图论 Kruskal 最小生成树算法

前置知识 关于最小生成树 先说「树」和「图」的根本区别&#xff1a;树不会包含环&#xff0c;图可以包含环 树就是「无环连通图」 生成树是含有图中所有顶点的「无环连通子图」 你要保证这些边&#xff1a; 1、包含图中的所有节点。 2、形成的结构是树结构&#xff08;即不…

NFS共享存储服务

目录 一、NFS简介二. NFS工作原理实验&#xff1a;准备一台服务器&#xff0c;一台客户端。实现共享目录服务器上发布共享目录配置操作客户端配置操作 总结 一、NFS简介 NFS&#xff08;Network File System 网络文件服务&#xff09; NFS 是一种基于 TCP/IP 传输的网络文件系…

五一国际劳动节知多少!祝五一劳动节快乐! Happy International Workers‘Day!

五一国际劳动节简称五一节&#xff0c;在每年的5月1日&#xff0c;它是全世界劳动人民的共同节日。5.1 International labor Days call 5.1 sections, May 1 in every year. It is the whole world labor common festival of the people. 劳动是人类的幸福之源。 Work is the t…

JQuery-原理示意图-- 选择器-- 选择器综合代码--jQuery 的 DOM 操作--增删改查节点--常用遍历节点方法--多选框应用--全部综合代码

目录 JQuery 基本介绍 jQuery 的原理示意图 JQuery 基本开发步骤 说明: jQuery简单示例 jQuery 对象和 DOM 对象 什么是 jQuery 对象 DOM 对象转成 jQuery 对象 应用实例 jQuery 对象转成 DOM 对象 代码演示 jQuery 选择器 jQuery 选择器介绍 jQuery 选择器的优…

Adaptive AUTOSAR 文档官方如何阅读

目前很多关于 Adaptive AUTOSAR 的文章都是官方文档的简化翻译&#xff0c;不如直接看官方文档更全面深入。 Adaptive AUTOSAR 文档官方下载地址 Adaptive Platform AUTOSARhttps://www.autosar.org/standards/adaptive-platform About The AUTOSAR Adaptive Platform impl…

JavaScript 教程---菜鸟教程

文章目录 JavaScript 教程JavaScript 输出JavaScript 对象JavaScript 函数JavaScript 事件 JS 函数JS 类JS HTML DOMJS 高级教程JS 浏览器 BOMJS 库 JavaScript 教程 JavaScript 输出 JavaScript 可以通过不同的方式来输出数据 使用window.alert()弹出警告框。 <script&…

物联网产品的开发的难点,致命点是什么?

物联网产品的开发的难点&#xff0c;致命点是什么&#xff1f; 当下是万物互联的时代&#xff0c; 物联网产品本身的难度因行业而异。但是物联网设备上云通信交互就成了各个行业需要首先解决的问题。 物联网通信问题从产品设计一开始&#xff0c;如果不能很好的解决&#xff0c…

C++引用详解

1.引用概念 引用不是新定义一个变量&#xff0c;而是给已存在变量取了一个别名&#xff0c;编译器不会为引用变量开辟内存空间&#xff0c;它和它引用的变量共用同一块内存空间。 比如&#xff1a; 这是简单的引用 注意&#xff1a;引用类型必须和引用实体是同一种类型。 2.…

数据仓库技术与Hive入门

文章目录 数据仓库基本概念场景案例主要特征主流开发语言-SQL数仓开发语言概述SQL语言介绍结构化数据SQL语法分类 Apache Hive入门Apache Hive 安装部署元数据 Hive SQL语言 数据仓库 基本概念 数据仓库(Data Warehouse,简称数仓、DW)&#xff0c;是一个用于存储&#xff0c;分…

FMC128:具有出色的同步性能-8通道同步采集

板卡概述 FMC128 是一款 8 通道 250MHz 采样率 16 位 AD 采集 FMC子卡&#xff0c;符合 VITA57 规范&#xff0c;可以作为一个理想的 IO 模块耦合至 FPGA 前端&#xff0c;8 通道 AD 通过高带宽的 FMC 连接器&#xff08;HPC&#xff09;连接至 FPGA 从 而大大降低了系统信号…

八、vue_options之computed、watch属性选项

一、computed计算属性使用 &#xff08;1&#xff09;复杂data的处理方式 &#xff08;2&#xff09;computed 计算属性 computed计算属性初体验&#xff1a; 在我们通过Vue调用createApp方法传入一个对象的时候&#xff0c;我们之前写了data属性、methods属性&#xff0c;这…

关于一个C++项目的总结与反思:bosot搜索引擎

文章目录 写在前面关于这个项目的收获简单的项目介绍整体逻辑与第三方库每一步的具体细节util.hppparser.ccindex.hppsearcher.hpphttp_server.hpp其他模块 项目地址&#xff1a;boost_searcher: 项目&#xff1a;boost站内搜索 (gitee.com) 写在前面 这个项目是用C写的&…

聚焦能源 | 赛宁网安亮相2023年中国能源网络安全大会

​​4月21日&#xff0c;2023年中国能源网络安全大会&#xff08;以下简称“大会”&#xff09;在江苏南京成功落幕&#xff01;为贯彻国家网络强国战略&#xff0c;加强能源网络安全技术创新、成果应用、人才培养与技术交流&#xff0c;大会推出主旨论坛、案例交流、展览展示等…

python:根据灰度值检查成像是否存在黑图情况

一、需求描述 1、摄像机在拍照的时候&#xff0c;会打开闪光灯进行拍照&#xff0c;假如闪光灯在拍照之后打开&#xff0c;就会产生黑图 2、因此&#xff0c;我们需要摄像机采集很多图片&#xff0c;检查是否每次拍照都是正常的 3、我们可以通过人眼进行查看&#xff0c;但是…

SpringCloud入门实战(七)-Hystrix服务熔断入门案例

&#x1f4dd; 学技术、更要掌握学习的方法&#xff0c;一起学习&#xff0c;让进步发生 &#x1f469;&#x1f3fb; 作者&#xff1a;一只IT攻城狮 。 &#x1f490;学习建议&#xff1a;1、养成习惯&#xff0c;学习java的任何一个技术&#xff0c;都可以先去官网先看看&…

Mysql 学习(七)独立表结构存储 一

独立表空间结构 InnoDB有很多类型表空间&#xff0c;这边主要是介绍独立表空间结构&#xff0c;因为这种会用的比较多讲之前我们先思考一个问题&#xff0c;如果我们以页为单位来分配存储空间的话&#xff0c;那两个页之间的物理距离可能很远&#xff0c;因为这是随机的&#…

2023有哪些适合学生用蓝牙耳机?300左右最好的蓝牙耳机推荐

2023年了&#xff0c;蓝牙耳机常常伴随手机出现在人们的日常生活当中&#xff0c;不管是听歌、运动、甚至玩游戏&#xff0c;大多数人都会选择戴蓝牙耳机。那么&#xff0c;有哪些适合学生用的蓝牙耳机&#xff1f;针对这个问题&#xff0c;我来给大家推荐几款300左右最好的蓝牙…