Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How does Java connect to MySQL database

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

Today, I would like to share with you the relevant knowledge about how to connect Java to MySQL database. The content is detailed and the logic is clear. I believe most people still know too much about this, so share this article for your reference. I hope you can get something after reading this article. Let's take a look at it.

First of all, it is stated that because it is a version 8 database, the writing of the configuration class is different from that of version 5. It should be noted that when using idea or eclipse, you need to import the jar package.

If you want to download a jar package with a different version of 8, you only need to change 8.0.28 to the specified version.

Idea imports the jar package as follows:

Then there is the code part, first create the table:

CREATE TABLE `train_ message` (`id` int NOT NULL AUTO_INCREMENT COMMENT 'primary key id', `train_ name` varchar (20) NOT NULL COMMENT' train name', `destination `varchar (30) NOT NULL COMMENT 'origin', `terminal`varchar (30) NOT NULL COMMENT 'final arrival' `departure_ time` timestamp NOT NULL COMMENT 'outbound time', `state` varchar (10) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT 'normal' COMMENT 'train status', PRIMARY KEY (`id`) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8mb3

Then the configuration class DbConfig.java,localhost that creates the connection is the local ip address. If there is a server, fill in the ip address of the server. Message is the name of the database. Here is a picture of names that are misunderstood by many beginners.

Import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;/** * database configuration class * @ author Jing ran * / public class DbConfig {public Connection dbConfig () throws SQLException {try {Class.forName ("com.mysql.cj.jdbc.Driver");} catch (Exception e) {System.out.print ("failed to load driver!") E.printStackTrace ();} String url = "jdbc:mysql://localhost:3306/message?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true"; String user = "root"; String password = "123456"; return DriverManager.getConnection (url, user, password);}}

Then write down the main function Main.java, where the function body of the main function can be written at the end, what function you need to open the comment, quick annotation method, select this sentence, press ctrl plus /, you can fully comment.

Import java.sql.SQLException;/** * main function, call function * @ author Jingran * / public class Main {public static void main (String [] args) throws SQLException {/ / new GetMessage () .getMessage (); / / new UpdateTrainState () .updateTrainState (); / / new InsertTrain () .insertTrain (); / / new GetNumber () .getNumber ();}}

Then there is the function of each:

1. Query the information of all trains from Shenyang to Wuhan and sort them by departure time.

Build GetMessage.java class

Import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;/** * query the information of all trains from Shenyang to Wuhan, sorted by departure time * @ author Jingran * / public class GetMessage {public void getMessage () throws SQLException {Connection con = new DbConfig (). DbConfig (); String sql = "select * from `train_ message` where origin =? And terminal =? ORDER BY departure_time ASC "; String origin =" Shenyang "; String terminal =" Wuhan "; PreparedStatement ps = con.prepareStatement (sql); ps.setString (1, origin); ps.setString (2, terminal); ResultSet rs = ps.executeQuery () Try {while (rs.next ()) {System.out.println ("Train name:" + rs.getString ("train_name") + "departure Station:" + rs.getString ("origin") + "final arrival:" + rs.getString ("terminal") + "departure time:" + rs.getString ("departure_time") + "Train status:" + rs.getString ("state") }} catch (SQLException e) {e.printStackTrace ();} finally {ps.close (); con.close ();}} 2. Modify the status of T2255 train to outage

Build UpdateTrainState.java class

Import java.sql.Connection;import java.sql.SQLException;import java.sql.Statement;/** * modify the T2255 train to be out of service * @ author Jingran * / public class UpdateTrainState {public void updateTrainState () throws SQLException {Connection con = new DbConfig (). DbConfig (); String sql = "UPDATE `train_ message`SET state = 'outage' WHERE train_name = 'T2255'"; Statement statement = con.createStatement () Try {int I = statement.executeUpdate (sql); if (I > 0) {System.out.println ("update successful");} else {System.out.println ("update failed");} catch (SQLException e) {e.printStackTrace () } finally {statement.close (); con.close ();}} 3. Add a new train information (enter it yourself)

Build InsertTrain.java class

Import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.SQLException;import java.util.Scanner;/** * add a new train information (input by yourself) * the departure time is timestamp, and you need to make sure that the format is correct when entering, such as: 2019-01-01 00:00:00 * @ author Jingran * / public class InsertTrain {public void insertTrain () throws SQLException {Connection con = new DbConfig (). DbConfig () Scanner scanner = new Scanner (System.in); String sql = "insert into `train_ message` values (null,?, default)"; System.out.print ("Please enter train name:"); String trainName = scanner.nextLine (); System.out.print ("Please enter departure station:"); String origin = scanner.nextLine () System.out.print ("Please enter final arrival:"); String terminal = scanner.nextLine (); System.out.print ("Please enter departure time:"); String departureTime = scanner.nextLine (); PreparedStatement ps = con.prepareStatement (sql); ps.setString (1, trainName); ps.setString (2, origin); ps.setString (3, terminal) Ps.setString (4, departureTime); try {int I = ps.executeUpdate (); if (I > 0) {System.out.println ("add successful");} else {System.out.println ("add failed");} catch (SQLException e) {e.printStackTrace () } finally {ps.close (); con.close ();}} 4. Query the number of trains with normal status

Build GetNumber.java class

Import java.sql.Statement;/** * query the number of trains with normal status * @ author Jingran * / public class GetNumber {public void getNumber () throws SQLException {Connection con = new DbConfig (). DbConfig (); String sql = "select count (state) from `train_ message`where state = 'normal'"; Statement statement = con.createStatement (); try {ResultSet resultSet = statement.executeQuery (sql) While (resultSet.next ()) {System.out.println ("the number of trains with normal status is:" + resultSet.getInt (1));}} catch (SQLException e) {e.printStackTrace ();} finally {statement.close (); con.close ();}

Finally, the attribute structure diagram of navicat and the statement inserted by the sample are attached.

Just write a few data according to your own needs. The above is the example code for java to connect to the mysql database, and eclipse is more or less the same, but the way to import the jar package is different.

These are all the contents of the article "how to connect Java to MySQL database". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report