RUVIDEO
Поделитесь видео 🙏

Java JDBC Tutorial - Part 5: Prepared Statements

📁 Лайфхаки 👁️ 20 📅 01.12.2023

NEED TO LEARN JAVA - 5 FREE JAVA VIDEO COURSES - CLICK HERE - https://goo.gl/7i95F8

---

View more videos on my "Java JDBC Tutorial" Playlist: http://goo.gl/crT4nS

Download Java Source Code: http://www.luv2code.com/jdbc-prepared-statements-mysql

Closed-Captioning and English subtitles available.

Please SUBSCRIBE to this channel: http://goo.gl/EV6Kwv

---

In this video tutorial we will learn how to use Prepared Statements.
- What are Prepared Statements
- Create a Prepared Statement
- Setting Parameter Values
- Executing a Prepared Statement
- Reusing a Prepared Statement

----

Follow luv2code:

Website: http://www.luv2code.com
YouTube: http://goo.gl/EV6Kwv
Twitter: http://goo.gl/ALMzLG
Facebook: http://goo.gl/8pDRdA

---

Join my mailing list: Get advance notice on new tutorials. Emails about 1 per week.
- http://www.luv2code.com/joinlist

---

Questions or problems? Post them in the comments section below.

---

Want to suggest a video? Leave a comment below. I'm always looking for new video ideas.

Let me know what video you'd like for me to create.

---
Transcript

Time - 00:00
Hi, this is Chad (Shod) with luv2code.com. Welcome back to another tutorial on Java and JDBC. In this video we will learn how to use Prepared Statements. We'll first define Prepared Statements. Next we'll learn how to create Prepared Statements. Then we'll set Parameter Values, execute a Prepared Statement, and finally reuse a Prepared Statement.

Time - 00:25
What exactly is a Prepared Statement? A Prepared Statement is simply a precompiled SQL statement. Prepared Statements provide the following benefits. They make it easier to set SQL parameters. They prevent against SQL dependency injection attacks, and they also may improve application performance since the SQL statement is precompiled.

Time - 00:50
For this tutorial we'll use the following table, employees. This table already has some sample data in it for testing. I have a SQL script that creates the table and also adds a sample data. You can download it from a link below. Inside of the download there's a file called sql/table-setup.sql. You can run this in your SQL tool to create the table and set up the sample data. Instead of hardcoding your SQL values in your statement, you can make use of parameter placeholders. You will use a question mark for the placeholder symbol. As you can see in this example, we replaced the hardcoded values with question mark placeholders.

Time - 01:29
Now let's look at adding Java code. You'll create a Prepared Statement by calling the constructor and passing it into SQL. Then when you're ready to execute the statement, you'll set the Parameter Values. The Parameter Values are set based on their data type and position. The parameter positions are 1 based, starting left going to right. Here we set the Parameter Value for salary and department. Then we execute the query by calling executeQuery. That's it. It'll return a result set, and we can process that result set in its normal fashion. Notice there's no need to provide the SQL since it was already provided earlier when we created the statement.

Time - 02:08
Now let's switch over to clips and see this in action. I have a simple driver program in place. Let's walk through the actual code. First we get a connection to the database. Then I make use of that Prepared Statement. Then from there I set the parameters. I set the first parameter for the salary of 80,000; the second parameter for the department of Legal. Then I'll execute the statement. This will give me a result set. Then I have a helper method that will display the result set. Now let's run this application to see the output. As you can see, this gave us the output for 3 employees, and they all meet the parameters. The salary is greater than 80,000; and they work in the Legal department.

Time - 03:02
Another advantage of Prepared Statements is that you can reuse the statement. If you need to run the same query again but with different Parameter Values, then all you have to do is set the new Parameter Values and execute the statement. Here what I'll do is I will add in a new section of code for our application to reuse the values from before. I'll just move down here, drop in another little snippet. We have this reuse statement. We're going to reuse our Prepared Statement. This time we're simply going to set the salary to 25,000 and set the department to HR. We set those parameters accordingly in our code. Then we go through and we execute the query.

Time - 03:41
Then we go and we display the result set. Let me save this one a bit, pull my window up, and run it one more time. Now I'll see some new output. Here's the reuse section. Note we have 4 employees here. Their salary is greater than 25,000; and they work for the HR department.


[snip] ... See Transcripts tab

Что делает видео по-настоящему запоминающимся? Наверное, та самая атмосфера, которая заставляет забыть о времени. Когда вы заходите на RUVIDEO, чтобы посмотреть онлайн «Java JDBC Tutorial - Part 5: Prepared Statements», вы рассчитываете на нечто большее, чем просто загрузку плеера. И мы это понимаем. Контент такого уровня заслуживает того, чтобы его смотрели в HD 1080, без дрожания картинки и бесконечного буферизации.

Честно говоря, Rutube сегодня — это кладезь уникальных находок, которые часто теряются в общем шуме. Мы же вытаскиваем на поверхность самое интересное. Будь то динамичный экшн, глубокий разбор темы от любимого автора или просто уютное видео для настроения — всё это доступно здесь бесплатно и без лишних формальностей. Никаких «заполните анкету, чтобы продолжить». Только вы, ваш экран и качественный поток.

Если вас зацепило это видео, не забудьте взглянуть на похожие материалы в блоке справа. Мы откалибровали наши алгоритмы так, чтобы они подбирали контент не просто «по тегам», а по настроению и смыслу. Ведь в конечном итоге, онлайн-кинотеатр — это не склад файлов, а место, где каждый вечер можно найти свою историю. Приятного вам отдыха на RUVIDEO!

Видео взято из открытых источников Rutube. Если вы правообладатель, обратитесь к первоисточнику.