How to connect to mysql from jdbc

How to connect to mysql from jdbc

How to connect to mysql from jdbc

When you are using JDBC outside of an application server, the DriverManager class manages the establishment of connections.

The following section of Java code shows how you might register MySQL Connector/J from the main() method of your application. If testing this code, first read the installation section at Section 3.3, “Connector/J Installation”, to make sure you have connector installed correctly and the CLASSPATH set up. Also, ensure that MySQL is configured to accept external TCP/IP connections.

Example 3.4 Connector/J: Obtaining a connection from the DriverManager

If you have not already done so, please review the portion of Section 3.6.1, “Connecting to MySQL Using the JDBC DriverManager Interface” above before working with the example below.

Once a Connection is established, it can be used to create Statement and PreparedStatement objects, as well as retrieve metadata about the database. This is explained in the following sections.

For Connector/J 8.0.24 and later: When the user for the connection is unspecified, Connector/J’s implementations of the authentication plugins use by default the name of the OS user who runs the application for authentication with the MySQL server (except when the Kerberos authentication plugin is being used; see Section 3.5.12.2, “Connecting Using Kerberos” for details).

A user name is considered unspecified only when the following conditions are all met:

The method DriverManager.getConnection(String url, String user, String password) is not used.

The connection property user is not used in, for example, the connection URL,or elsewhere.

Notice if (1) or (2) is not true and an empty string is passed, the user name is an empty string then, and is not considered unspecified.

How to connect to mysql from jdbc

When you are using JDBC outside of an application server, the DriverManager class manages the establishment of connections.

The following section of Java code shows how you might register MySQL Connector/J from the main() method of your application. If testing this code, first read the installation section at Chapter 4, Connector/J Installation, to make sure you have connector installed correctly and the CLASSPATH set up. Also, ensure that MySQL is configured to accept external TCP/IP connections.

Example 7.1 Connector/J: Obtaining a connection from the DriverManager

If you have not already done so, please review the portion of Section 7.1, “Connecting to MySQL Using the JDBC DriverManager Interface” above before working with the example below.

Once a Connection is established, it can be used to create Statement and PreparedStatement objects, as well as retrieve metadata about the database. This is explained in the following sections.

For Connector/J 8.0.24 and later: When the user for the connection is unspecified, Connector/J’s implementations of the authentication plugins use by default the name of the OS user who runs the application for authentication with the MySQL server (except when the Kerberos authentication plugin is being used; see Section 6.12.2, “Connecting Using Kerberos” for details).

A user name is considered unspecified only when the following conditions are all met:

The method DriverManager.getConnection(String url, String user, String password) is not used.

The connection property user is not used in, for example, the connection URL,or elsewhere.

Notice if (1) or (2) is not true and an empty string is passed, the user name is an empty string then, and is not considered unspecified.

Как использовать базу данных MySQL в Java

How to connect to mysql from jdbc. Смотреть фото How to connect to mysql from jdbc. Смотреть картинку How to connect to mysql from jdbc. Картинка про How to connect to mysql from jdbc. Фото How to connect to mysql from jdbc

Кстати, если вы ищете хорошую книгу по использованию JDBC, обратите внимание на Practical Database Programming with Java (Ying Bai). Это относительно новая книга, и в ней рассматриваются две самые популярные базы данных: Oracle и SQL Server 2008. В книге используется IDE NetBeans для примеров и описываются все инструменты, необходимые для работы с базами данных в Java. Это отличная книга для начинающих и опытных программистов.

Подключаем базу данных MySQL с помощью JDBC

Для того, чтобы подключить базу данных MySQL, нам потребуется четыре вещи:

и наполнить её хорошими книгами:

Программа на Java, которая использует базу данных

Успешный запуск программы выведет на экран следующее:

Результат верный, поскольку у нас в таблице только две книги: «Effective Java» и «Java Concurrency in Practice».

Получаем данные с помощью SELECT-запроса в JDBC

Для получения данных из БД вы можете выполнить SELECT-запрос. В первом примере мы уже его использовали, но получили только количество строк. Теперь мы вернем сами строки. Большая часть программы останется без изменений, за исключением SQL-запроса и кода, возвращающего данные из объекта ResultSet :

Этот код выведет на экран следующее:

Добавляем данные с помощью INSERT-запроса в JDBC

После запуска программы вы можете проверить таблицу в СУБД. На этот раз вы увидите три записи в таблице:

How to connect to mysql from jdbc. Смотреть фото How to connect to mysql from jdbc. Смотреть картинку How to connect to mysql from jdbc. Картинка про How to connect to mysql from jdbc. Фото How to connect to mysql from jdbc

Когда разберетесь с подключением и простыми запросами, имеет смысл изучить, как использовать подготавливаемые запросы (Prepared Statement) в Java для избежания SQL-инъекции. В боевом коде всегда следует использовать подготавливаемые запросы и связывание переменных.

Если вам понравилось это руководство и не терпится узнать больше о подключении и работе с базой данных из Java-программ, обратите внимание на следующие статьи:

Connecting to MySQL Using JDBC Driver

In this tutorial, you will learn how to connect to MySQL database using JDBC Connection object.

To connect to MySQL database from a Java program, you need to do the following steps:

Loading MySQL Connector/J into your program

To load MySQL Connector/J into your program you follow three steps below:

First, in NetBeans IDE, from project name, right mouse click and choose properties menu item. The project properties dialog will appear.

How to connect to mysql from jdbc. Смотреть фото How to connect to mysql from jdbc. Смотреть картинку How to connect to mysql from jdbc. Картинка про How to connect to mysql from jdbc. Фото How to connect to mysql from jdbc

Second, on the left hand side of the project properties dialog, from the Categories section, choose Libraries item.

How to connect to mysql from jdbc. Смотреть фото How to connect to mysql from jdbc. Смотреть картинку How to connect to mysql from jdbc. Картинка про How to connect to mysql from jdbc. Фото How to connect to mysql from jdbc

Third, click on the Add JAR folder button, browse to the location where you installed MySQL Connector/J, and choose the JAR file as screenshot below; after that click OK button.

How to connect to mysql from jdbc. Смотреть фото How to connect to mysql from jdbc. Смотреть картинку How to connect to mysql from jdbc. Картинка про How to connect to mysql from jdbc. Фото How to connect to mysql from jdbc How to connect to mysql from jdbc. Смотреть фото How to connect to mysql from jdbc. Смотреть картинку How to connect to mysql from jdbc. Картинка про How to connect to mysql from jdbc. Фото How to connect to mysql from jdbc

Connecting to MySQL database

First, you need to import three classes: SQLException, DriverManager, and Connection from the java.sql.* package.

Second, you call the getConnection() method of the DriverManager class to get the Connection object. There are three parameters you need to pass to the getConnection() method:

From Java 7, there is another nice statement called try-with-resources that allows you to simplify the code above as follows:

It is automatically calls the close() method of the Connection object once program finishes. As you can see it’s cleaner and more elegant. However…

It is not secure as well as flexible when you hard coded the database parameters inside the code like above. In case you change the database server or password; you have to change the code, compile it again, which is not a good design.

To avoid hard coding all the database parameters in the code, you can use a Java properties file to store them. In case of changes, you just need to change them in the properties file and you don’t have to recompile the code.

Let’s take a look at the properties file named db.properties:

You can rewrite the code for creating a Connection object with parameters from a properties file as follows:

For each interaction with MySQL database, you need to create a new connection. You would have the same piece of code for doing this in all places. Rather than doing this, you can create a new class for handing connection creation:

From next tutorial, we will use this MySQLJDBCUtil class for creating a new connection to MySQL as follows:

In this tutorial, we have shown you step by step how to connect to MySQL using JDBC Connection object and use properties file to store database parameters. At the end of the tutorial, we developed a utility class that you can reuse it every time you create a connection to the database.

Connect Java to a MySQL database

How do you connect to a MySQL database in Java?

When I try, I get

14 Answers 14

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

Here’s a step by step explanation how to install MySQL and JDBC and how to use it:

Download the JDBC driver and put in classpath, extract the ZIP file and put the containing JAR file in the classpath. The vendor-specific JDBC driver is a concrete implementation of the JDBC API (tutorial here).

If you’re using an IDE like Eclipse or Netbeans, then you can add it to the classpath by adding the JAR file as Library to the Build Path in project’s properties.

Create an user for Java and grant it access. Simply because using root is a bad practice.

Yes, java is the username and password is the password here.

Determine the JDBC URL. To connect the MySQL database using Java you need an JDBC URL in the following syntax:

So the final URL should look like:

Test the connection to MySQL using Java. Create a simple Java class with a main() method to test the connection.

Note that you don’t need to load the driver everytime before connecting. Just only once during application startup is enough.

To solve the one or the other, follow the following advices:

That was it as far the connectivity concerns. You can find here a more advanced tutorial how to load and store fullworthy Java model objects in a database with help of a basic DAO class.

Источники информации:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *