Connection with a database code example

Example 1: database connection

Connection = 
  Helps our java project connect to database
Statement = 
  Helps to write and execute SQL query
ResultSet = 
  A DataStructure where the data from query result stored
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    

  After succesfully created the connect
next step is STATEMENT

Statement statement = connection.createStatement();
We use createStatement() method to create
the statement from our connection.
-The result we get from this type of statement
can only move from top to bottom,
not other way around

Statement statement = connection.
createStatement(ResultSet TYPE_SCROLL_INSENSITIVE
,ResultSet CONCUR_READ_ONLY);

-The result we get from this type of
statement can freely move between rows

Once we have statement we can run
the query and get the result to
ResultSet format 
		import java.sql.ResultSet;
        
We use the method executeQuery()
to execute our queries

ResultSet result = statement.
              executeQuery("Select * from employees");

Example 2: connecting to the database

const mysql = require('mysql');

// First you need to create a connection to the database
// Be sure to replace 'user' and 'password' with the correct values
const con = mysql.createConnection({
  host: 'localhost',
  user: 'user',
  password: 'password',
});

con.connect((err) => {
  if(err){
    console.log('Error connecting to Db');
    return;
  }
  console.log('Connection established');
});

con.end((err) => {
  // The connection is terminated gracefully
  // Ensures all remaining queries are executed
  // Then sends a quit packet to the MySQL server.
});

Tags:

Php Example