Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Problems
  • Python
  • C
  • C++
  • Java
  • Courses
  • Machine Learning
  • DevOps
  • Web Development
  • System Design
  • Aptitude
  • Projects
Open In App
Next Article:
How to Connect to a MongoDB Database Using Node.js
Next article icon

How to connect MySQL database using Scala?

Last Updated : 26 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

MySQL database connectivity using Scala

Introduction:

  • Since Scala is interoperable with Java, we can directly work with databases using JDBC.
  • JDBC - Java DataBase Connectivity is a Java API that allows Java code or programs to interact with the database.
  • Scala code blocks or programs similarly use these JDBC APIs in Java programs.
  • Using this JDBC API, we will establish Database connectivity using Scala.

To do the same, you need the jar file and for that, you can even locate the jar file in that directory where the file is located itself or provide the classpath while compiling.

For the above query, refer to this: JAR files in Java

Now let's see simple database connectivity code using Scala.

Scala
import java.sql.{Connection, DriverManager, SQLException} object DatabaseConnectivity extends App {      //JDBC url for connectivity   val jdbcUrl = "jdbc:mysql://localhost:3306/test"   val uname = "root"//MySQL username   val pwd = ""//MySQL password   val connection: Connection = null      // try block for connectivity and if error or    // exception occurs it will be catched by catch block   try{          //Load Driver Class     Class.forName("com.mysql.cj.jdbc.Driver")          // Establish connection using url,     // mysql username an password     connection = DriverManager.getConnection(jdbcUrl, uname, pwd)     println("Connection successful!!")   } catch{     case e : ClassNotFoundException =>       println("Error loading jdbc driver class!!")       e.printStackTrace()     case e: SQLException =>       println("Error Connecting to the database!!")       e.printStackTrace()   } } 

The above code is very simple and basic code for the Scala connectivity with the MySQL database using JDBC.

  1. Import all required or specific classes required for the connection and program execution. The line 'import java.sql.{Connection, DriverManager, SQLException}' imports the classes from java.sql package.
  2. Then we defined an object named 'DatabaseConnectivity' in which we wrote the entire code.
  3. Then we defined 4 immutable variables using val. Following are the variables. First variable 'jdbcUrl' for JDBC Url for connectivity. Here 'test' in the url is the name of the database. Variables 'uname' and 'pwd' are used to hold MySQl username and password for connectivity and the last variable 'connection' is of Connection type, this will hold the actual connectivity statement.
  4. Next we have try-catch block for executing block of code properly with exceptions handled in try-catch block.
  5. In try block, we have 'Class.forName' is used for loading the driver class. Next we have connectivity of the database assigned to this variable with the url, username and password. The connection is established using DriverManager.getConnection() method.
  6. Next, if the connection is successfully established, then println in try block is executed with output "Connection successfull".
  7. If there was error in the connection then, the execution flow is carried out by catch block where it gives output as per the error or exception occurred.
  8. In first case returns the output when the JDBC driver class is not found. And the second case returns output when there was some SQL Exception. The 'printStackTrace()' prints a detailed information about the exception or error that occured during the execution.

Lets see the output of the code block:

Screenshot-2024-03-20-230612
No error or Exception occurred during the execution and the connection was successful

For more details or to know more about the same you can refer to this database Connectivity with java for more clearance: Java Database Connectivity with MySQL


Next Article
How to Connect to a MongoDB Database Using Node.js

M

mihikaphsj
Improve
Article Tags :
  • Scala

Similar Reads

  • Connecting to SQL Database using SQLAlchemy in Python
    In this article, we will see how to connect to an SQL database using SQLAlchemy in Python. To connect to a SQL database using SQLAlchemy we will require the sqlalchemy library installed in our python environment. It can be installed using pip - !pip install sqlalchemyThe create_engine() method of sq
    3 min read
  • How to Connect Python with SQL Database?
    In this article, we will learn how to connect SQL with Python using the MySQL Connector Python module. Below diagram illustrates how a connection request is sent to MySQL connector Python, how it gets accepted from the database and how the cursor is executed with result data. To create a connection
    2 min read
  • How to Connect to a MySQL Database Using the mysql2 Package in Node.js?
    We will explore how to connect the Node.js application to a MySQL database using the mysql2 package. MySQL can be widely used as a relational database and mysql2 provides fast, secure, and easy access to MySQL servers, it can allow you to handle database queries efficiently in Node.js applications.
    6 min read
  • How to Connect to a MongoDB Database Using Node.js
    MongoDB is a NoSQL database used to store large amounts of data without any traditional relational database table. To connect to a MongoDB database using NodeJS we use the MongoDB library "mongoose". Steps to Connect to a MongoDB Database Using NodeJSStep 1: Create a NodeJS App: First create a NodeJ
    4 min read
  • How to Connect to MySQL Server
    MySQL is a widely utilized open-source relational database management system (RDBMS) known for its popularity and effectiveness in handling and structuring massive amounts of data. If you are a developer, data analyst, or someone who needs to store and manage data, MySQL is a highly adaptable and de
    5 min read
  • How to connect to SQLite database that resides in the memory using Python ?
    In this article, we will learn how to Connect an SQLite database connection to a database that resides in the memory using Python. But first let brief about what is sqlite. SQLite is a lightweight database software library that provides a relational database management system. Generally, it is a ser
    3 min read
  • How to Migrate an Oracle Database to MySQL
    Migrating databases between different platforms is a common task in the world of data management. Whether you're consolidating databases, switching to a different database management system (DBMS), or moving to a more cost-effective solution, migrating from Oracle to MySQL can be a complex but rewar
    5 min read
  • Java Database Connectivity with MySQL
    In Java, we can connect our Java application with the MySQL database through the Java code. JDBC ( Java Database Connectivity) is one of the standard APIs for database connectivity, using it we can easily run our query, statement, and also fetch data from the database. Prerequisite to understand Jav
    3 min read
  • MySQL Create Database Statement
    The MySQL CREATE DATABASE statement is used to create a new database. It allows you to specify the database name and optional settings, such as character set and collation, ensuring the database is ready for storing and managing data. In this article, we are going to learn how we can create database
    4 min read
  • How to Connect to a MongoDB Database Using the Node.js Driver ?
    MongoDB is a popular, open-source, NoSQL (non-relational) database that provides high performance, high availability, and easy scalability. Unlike traditional relational databases, MongoDB stores a JSON-like format called BSON (Binary JSON). In this article, we connect the MongoDB database to your b
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences