> 文章列表 > 【MYSQL】Java的JDBC编程(idea连接数据库)

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

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

1. 配置

(1)新建一个项目
【MYSQL】Java的JDBC编程(idea连接数据库)

(2)Build System 那里选择Maven,下一步Create
【MYSQL】Java的JDBC编程(idea连接数据库)
(3)配置pom.xml文件
首先查看自己的MYSQL版本:进入MySQL命令窗口
【MYSQL】Java的JDBC编程(idea连接数据库)

我的MYSQL版本是8.0版本的.

下一步,去Maven官网:Maven
点击搜索框,输入Java,回车
【MYSQL】Java的JDBC编程(idea连接数据库)
点击下图这个:
【MYSQL】Java的JDBC编程(idea连接数据库)
找到对应版本点击进去,比如我的是8.0.28,那我就点即8.0.x最新版的8.0.33。
【MYSQL】Java的JDBC编程(idea连接数据库)
下拉,点击Maven,复制里边的代码。
【MYSQL】Java的JDBC编程(idea连接数据库)
回到我们刚创建的Java项目,在pom文件中
先写以下代码:

<dependencies>  </dependencies>

再把刚才从Maven中复制的代码放到上面代码的中间。(通常情况会报错,这是正常的):
【MYSQL】Java的JDBC编程(idea连接数据库)
(4)setting文件

新建一个setting文件,文件后缀是.xml,然后在文件中填入下面的代码,记住文件路径,记得保存。
【MYSQL】Java的JDBC编程(idea连接数据库)

<?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 athttp://www.apache.org/licenses/LICENSE-2.0Unless 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文件路径。
【MYSQL】Java的JDBC编程(idea连接数据库)

做完上面的之后,手动点一下下面的图表,重新加载pom(过程可能有点慢)
【MYSQL】Java的JDBC编程(idea连接数据库)
最后出现下图的结果配置就完成了。
【MYSQL】Java的JDBC编程(idea连接数据库)

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;}@Overridepublic 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中的datasourcedataSource = 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. 执行SQLresultSet = 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 测试结果

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